A c tutorial by:R3D
#include <stdio.h>
int main()
{
printf("Hello universe!\n");
return 0;
}
The largest step to becomming a programmer is making your first steps, and
writing your first program is a difficult task. While this program looks easy
enough for me, I am certain you have no idea what anything you have just seen
does, and you should be in a state of confusion. The good news is, I am about to
go over this program line by line, explaining every component. Sit tight.
Lets Take a Good look at this program.
#include <stdio.h>
Finally we are writing code, but not without a metaphoric example. Lets say you
have a new job, you have been given many new instructions by your boss, but you
do not know howto do them. In order to be able to do these jobs, you must know
how! But wait a minute, you ask.. cant you just employ someone that does know
how, and your boss will never find out.. The answer is YOU CAN! As with this
first line, you must tell the computer that you wish to 'include' instructions
from a file that already contains ready to go functions. As you will soon find
out, you need the file 'stdio.h' so that you can use instructions from it, for
example, printf(); I will make it clear right now, that the C programming
language contains no input and output routines. This means, the C language
itself contains no functions that directly allow the user of the program to type
in their name etc. Luckily however for the programmer, a set of standard
reusable functions were created. You can include these functions into your
program by including the name of file which contains the functions you wish to
access. For example, you may want to write a program that gets the system time,
C contains no time functions, so you must include 'time.h' and use functions to
do the work. The name given to this large set of include files is the standard
library. You will be using it often if you persue C.
int main()
Ok so we have included the header file 'stdio.h' that contains the function
printf so that we can display a string on the screen. Before we make our program
call upon printf() we must define the beginning of the program. In context, we
must tell our program where to start, so that it can begin doing its thing.
Every program in C is begun with the one function:
int main()
{
/* Execute instructions here */
}
As shown here, our neat little program defines its own start by the use of int
main { }. If you are wondering what the parenthesis marks are for (parenthesis
are { and } ) worry no further! As soon as we tell our program where it is to
begin, we must also tell it which data is to be used throughout the program. By
containing the program instructions between the two parenthesis, our program
knows where and when the program exits.
NOTE: Comment your programs!
Although up until now, You have not seen or been told about comments, they are
neccessary in making your work neat and readable, in due time other people will
be reading your code, and to make it as readable as possible is very important.
If you comment your work, it will be much others for people to read. A comment
is in the form of:
/* Comment */
Or your comment can span over multiple lines like this:
/*
This is also
a
valid
comment
*/
Ok hopefully all should be clear to you at the moment, the next part is probably
the most difficult to understand, but still relatively easy. This part is where
the core of your program takes place, up until now, we have programmed the
skeleton of the program, it is not until now, that we are able to execute
machine instructions. In our case, we are executing a function called 'printf'
which is contained within the standard library. The syntax for printf is as
follows:
int printf(const char *format, ...)
For now just note *format will be the string you wish to give to printf as in
our program, ignore the second parameter.
Wait a minute, hold up... I know what your thinking, You were going great, and
now hes bombarded me with a killer line of code that will leave me dazzed and
confused. Wrong, What I have just showed you is the correct definition for
printf, and I will easily make this definition clear to you..! The reason printf
contains 'int' before it, is that it is a function contained within the standard
library, and generally most functions return a value after they have completed
what they are meant to do. In printf's case, it returns the number of characters
displayed. So if we did this:
printf("Boat");
printf would return the numerical value '4'. Do you see? If you dont, dont worry
to much as you definately dont need to know anything about functions yet.
However you would be smart to learn the arguments that printf takes. The
function printf() is designed to allow the programmer to print data to standard
output, which is in most cases the screen. If however, you wish to print a
string, and a number in one shot, you must take full advantage of printf's
variety of features. They will be explained in detail further down the track.
Keep refferring back to the example at the top of this page to see how all of
this fits in, and remember, dont forget to add the > > } < < at the end of your
program, to symbolise the end of the main program.
Well that raps it up for the extreme basics.. Hope I helped you understand howto
create a simple application. Read on to see how you can extend the program shown
above. Before going on, I recommend you compile this program above by following
these simple steps:
1: Install your compiler
2: Write the program above to a file called hello.c
3: Save hello.c and exit the text editor
4: Go into dos, and type:
gcc hello.c -o hello
And then run hello.exe by typing:
hello.exe
at the command line.
The output should look like this:
c:\hello.exe_
Hello Universe!
C:\_
Before we look at a more defined example, let me explain why I added '\n' to the
end of the string we displayed. In order for your program to add a new line to
the end of what printf displays you must include the NEW LINE character. '\n'
should be included when neccessary. Try compiling the above program without it.
And then try doing it with more than one NEW LINE characters.
Exercises:
1: Create a Program that displays your name and age.
2: Create a program that displays your name and age on seperate lines, using
only one printf statement.
3: Write a program that displays a box like this:
****
* *
* *
****
Now let us program an application that accepts input from the user, from the
keyboard, stores this input into a buffer (string) and then displays that string
to the user. When broken down our program will contain these three simple steps:
1: Ask For Input
2: Store input into variable (string)
3: Print value contained in variable (string)
Before showing you the program, observ a function we have not yet seen. Very
similar to Printf(), except that it asks the user for input and saves that input
into a variable, which we will declare as a string.
The function for scanf is as follows:
int scanf( const char *format ,[argument]... );
This time, TRY to understand that format is the string that you are inputing,
and the argument is the address of the variable in which you are storing the
string. Our new program now looks like this:
#include <stdio.h>
int main()
{
char string;
printf("Enter Your Name:");
scanf("%s", string);
printf("Your name is %s\n", string);
return 0;
}
As seen above, we have done something new.. we have created our own variable!
Variables are handy to a programmer because they allow you to store your data
somewhere. Picture a variable as a wallet, where the data is the money. Or
picture a variable as an empty bucket, just waiting to be filled with water.
When you issue the command:
int age; age = 16; you are filling the wallet/bucket with the value 16. As far
as we are concerned it could be 16 dollars or 16 litres of water, but the
computer likes to see things from a different perspective. Because we declared
age as an integer (int) the compiler will expect our code to fill 'age' with a
number, rather than money or water. When learning abstract things it is often
easier to associate what you are learning with things you already know about. So
whilst learning C, or anything else, create wallets and buckets wherever
possible. This will be an invaluable memory aid.
To create your own variables, simply type the C name of the variable you wish to
create, followed by the name you wish the variable to have. Here are some
examples:
int variable; ---> more likely int Total_Cost;
char variable; ---> more likely char name;
After a variable is created, it can then be called upon by your program, to
either be filled with data. Or it could be used to take data from. So with a
little imagination..
Once a variable is declared it could be seen as a bank teller. By constructing
the variable, you are creating the bank teller, which will allow you to store
money, and take money. I will now give an example to do with the usage of a
variable, extracting from a variable and storing data in a variable:
Example - Storing and extracting data using variables
int number1, number2;
number1 = 5 + 2; /* number1 = 7 */
number2 = number1 + 3; /* number2 = 10 */
Hopefully it can be easily seen how the above snippet of code works. Two
variables are created and data is stored into both. When storing data into the
'number2' variable we can then ask for the contents of the 'number1' variable.
So number2 will equal what is in number1 + 3, which will equal 10.
So now scanf can be understood -> >
scanf asks for the type of data to input, and the address of the variable to
fill with this data.
type of variable location of variable
scanf("%c ", variable );
Some examples of type are:
%c -- character input -- 'c' or 'a' or 'Y'
%s -- string input -- 'dog' or 'plane' or 'abcdef'
%d -- integer input (number) -- '45' or '146' or '99999'
%f -- floating point number -- '2.5' or '45.322' or '23455.4334'
Again compile this program by following these simple steps:
1: Copy the above code into a text editor and save it as name.c
2: At the dos prompt, type the compile command:
gcc name.c -o name
3: Run the program by typing this:
C:\name.exe <-- or wherever you compiled the program
The output will be exactly like this:
C:\name.exe_
Enter Your Name: John_
Your Name is John
C:\_
Once again, you have seen something new. I advice you play with scanf ALOT until
you feel more than confident to progress on!
Exercises:
1: Write a program that asks for their name and their phone number.
TIP: To accept numbers using scanf() use this code:
int variable;
scanf( " %d ", & variable);
For now, all you need to know is that the '&' character must be used before
variables of type integer because you are storing the input directly into a
memory location. Which is what the '&' symbol means.
NOTE: You do not need to include the '&' symbol in front of strings.
2: Write a program that asks for their name and displays their name on the
screen five times.
3: Write a program that adds two numbers, note what happens!
Right about know you might be pretty worried, because exercises 2 and 3 above,
did not compile correct? That is because you tried to store an integer value
into a string, this is elligal in C, here is why:
C contains many data types, each containing its own characteristics and uses.
The two main storage types I am interested in right now are int and char. Let me
show you a simple application that will answer most of your queries. If still in
doubt, compile it like you did the others, and play with it :
#include <stdio.h>
int main()
{
int sum = 0;
int number1, number2; /* Declare two integers */
number1 = number2 = 0; /* Set both variables to 0 */
printf("Please Enter two numbers :");
scanf("%d %d", &number1, & number2);
sum = number1 + number2;
printf("The total of %d + %d is %d!\n", number1,number2,sum);
return 0;
}
Output:
C:\program.exe_
Please enter two numbers:
4_
10_
The total of 4 + 10 is 14
C:\_
The code on this page is rather simple, but contains many fundamental concepts,
that are needed if you wish to become a brave programmer .
Hints
To store an integer value into a variable (defined as int dont forget to include
an & in front on the variable eg:
scanf("%d",&variable");
When dealing with strings, you dont need to include the & character. Eg:
scanf("%s", charvariable);
Always create a third variable for the addition of two other variables as it
aids program readability and it makes you code more efficient.
Make your programs clearer by including comments eg:
/* This is a comment */
/* This is a
multiline comment
*/
Dont forget to open with /* and end with */ a common mistake eg: */ This is not
a correct comment /*
FINAL TIP FOR THIS SESSION:
Manipulate the programs i have given until you feel confident enough to write
one for yourself.
When your ready...