Left Quote    Knowledge speaks, but wisdom listens.
- Jimi Hendrix    
Right Quote
[login] | [Register]

C Tutorial

by: Jester
Page: 1 of 10
(View All)


C is an extremely powerful programming language. C is a language written by programmers for programmers, it became the most popular programming language ever in 1978. UNIX, its tools, and C were developed almost simultaneously; C grew up with UNIX but has since then left its home and is available on just about every computer system around. The development of C is not over, a researcher Bjarne Stroustrup Of Bell Laboratories began experimenting with an object orientated flavour of C that he called C++ (c plus plus). C++ extended C, in Bjarne's words "making a better C". This tutorial focuses on C, not C++. The X3J11 committee have adopted some of Bjarne's proposals into the ANSI C standard and since then an ANSI C++ standard has been created.

C++, however, didn't take over from C. C++ isn't for everyone and when learning C it's advised that you stick to the basics, learn to program in C, and when you're ready, move onto object-orientated C++.

C is a compiled language. For those of you that know Perl or PHP, you know that you write the source code and the Perl or PHP interpreter compiles the script on the fly (or interprets it). With C you must compile your source code into "machine language" before you can run the program. You write the source code, compile that source code into machine language that the computer can understand, and then run your program. Here is what you need to do:

  • Install a Compiler, there are many out there.
  • Learn the Basics of C.
  • Compile your source code into machine code and run the program.

Let's go on and learn more about compilers.


When you have written your C program in source code, you must then compile it into machine code.

As it says on whatis:

"A compiler is a special program that processes statements written in a particular programming language and turns them into machine language or "code" that a computer's processor uses. Typically, a programmer writes language statements in a language such as Pascal or C one line at a time using an editor. The file that is created contains what are called the source statements. The programmer then runs the appropriate language compiler, specifying the name of the file that contains the source statements."

So basically, a compiler converts source code into executable code that can be processed by your computer. Source code enables the programmer to write a program at a higher level and logically spell out what they want the program to do. The compiler then converts these logical steps into a language the processor can understand.

Which Compiler?

There are many compilers to choose from, and it depends what operating system you're using, but here are a couple links to compilers that are quite popular.

  • Borland's Site - Borland are currently giving away Borland C++ 5 for free.
  • DJGPP - DJGPP is a free compiler that has its own graphics library. It's a pretty big download and can be tricky to set up, but it's worth it.
  • BloodShed - Another free compiler, a 6MB download, very easy to set up and it runs in windows.

Remember, C++ compilers can also compile pure C source code, so you may as well get a C++ compiler, as if you ever move onto C++ you wont have to download a separate compiler.

Ok that clears compilers up, let's take a look at a simple C program. It'll have to be simple as I'm very new to C, so I can only cover the very basics.

Hello World Program

Take a look at the simple program below:

If you're completely new to C that'll probably look confusing, so let's go through it:

#include <stdio.h>

This line does what it says it does, it includes the header file "stdio.h" - stdio means "standard input/output. This "header" file contains ready-to-go functions for your program. Without this file you would have to write your own functions to input and output data, but why should you when others have done it for you? You can simply include their functions that are stored in the header file into your program and use these functions. If you know Perl or PHP this may seem weird (it did for me) but C's functions aren't "built-in" as they are in Perl and PHP, you have to include the appropriate header files containing the functions you wish to use in your program.

/*My first program*/

This line is a comment, anything between /* and */ is a comment and will not be compiled. Comments are used to, of all things, comment your source code. If you get into C and start writing programs that interest others, sooner or later others will be reading your source code. To help them follow it more easily comment it, tell them what's happening at each step, commenting = good. A comment can span multiple lines, just contain it between the comment symbols.

int main()

We have included our header file and have the functions contained within it available to us, now we need to make the program do something. But before we do anything we must tell the program where to start and where to finish.

This defines where the program starts and where it ends, we contain the program instructions between the curly braces. All C programs must contain this if nothing else.

printf("Hello World!n");

This is the printf() function. It is contained within the "stdio.h" file we included earlier. Our little program simply prints "Hello World!" to the screen. This is what prinf() does. We don't need to cover functions yet, just take note of this, we give printf() the string "Hello World!" and printf() outputs it (prints it to the screen). printf() has more features, we'll see one of these in the next chapter. The n character just means a new line, so after we print "Hello World!" take the pointer down to the next line.

return 0;

This tells the main() function to return, in this case it just means end it. This isn't necessary, it depends which compiler you're using, so it's a good idea to include it just incase.

Save this little program to a file called "hello_world.c". You need a compiler (see last chapter). Then compile it and watch what it does, congratulations you just compiled your first C program.

This is the extreme basics of C, but we all have to start somewhere, the hardest part if you're completely new to programming is getting started, hopefully this chapter got you started and explained a few things to you.


Defining variables in C is pretty simple. Again, if you know Perl or PHP this may seem a little strange, alot of C might, but it's worth learning this powerful language.

When we define a variable in C we must define what type it is, aswell as its name.

int MyNumber;

The above define a variable named "MyNumber" that can handle integer values. Meaning this variable can only contain number values, not fractional numbers, whole numbers. There are a few types of variables:

We must know what kind of data the variable will contain, variable names are case-sensitive, We cannot have two variables with the same name, we cannot have two functions with the same name. We can also define two variables of the same type in one go:

int FirstNumber, SecondNumber;

We could define as many variables as we wanted. When we make a variable we are giving a name to our data. Any data you store in that variable is stored in a location in memory associated with that variable. So when we use the variable in later functions or operations, you can access it by a name, it makes it easier for us humans to solve problems this way.

We can also define a variable and give it a value all in one go:

Let's have a look deeper into printf(), let's use a variable with it.

We have used an extra parameter with printf(). If we want to use a variable with printf() we must first enter the text to be printed, follow it by a comma, and then the variable name.

"The number is %d"

What's that %d? That's where the value stored in the variable will be printed out. The second parameter is the variable name, and the %d is the place in the printf() string where we want that value to appear. If we did:

printf("The number %d is", Number);

The program would read "The number 4 is", get it? As there are many types of variable, we must use the correct sign to output a variable in printf(), there are different ones depending on the type of data contained in the variable.

So if the variable contained a character:

We would use %c to show that the data stored in "Letter" is the type "char". We can use many variables in a printf() function.

Will print "The sum of 3 and 5 is 8". Just keep the %d signs in order with the variable parameters on the right, as simple as that.


We can manipulate the data contained in a variable by using operators.

We can also copy variables

Number1 = Number2; /*Number1 now contains same data as Number2*/

Taking Input

We can use the scanf() function to take input from the person running the program and assign the value to a variable. Here's how it looks:

scanf("%d", &Number);

As with printf() we must use the right sign, here we will be dealing with an integer so we use %d. The second parameter is the variable to which we want to assign the value.

Now this program is more interesting. It asks the program user for input. It then assigns the first integer value to Number1:

scanf("%d", &Number1);
Then it asks them for another number and assigns that to Number2:

scanf("%d", &Number2);
The it adds the two values together and prints out the result:

Sum = Number1 + Number2;
printf("The sum of %d and %d is %d", Number1, Number2, Sum);

But you ask, why does the variable name have a '&' in front of it? Well when we're dealing with scanf() we must preceed the variable name with that '&' sign. You must do this because you are storing the input directly into a memory location. For now, just don't forget the '&'.

Let's do it with a char.

scanf()is a very useful function, play around with it for a while, try modifying the program a little, maybe take two letters. When you're happy continue.


Pointers are an important part of C. If you don't understand how pointers work, you use alot of the power and flexibility of C. Pointers are difficult to understand if you don't try.

We define a pointer like so:

int *p;

The * shows that this isn't a variable, it's a pointer. A pointer does what it says, it points. Also, the pointer must be a certain type, as with variables. if it's going to point to an integer, we define it as an integer pointer. Let's have another look:

Remember the '&' sign from the last chapter? What this sign means is, instead of assigning the "value" of num to the pointer, we actually assign the address in memory where the data for num is stored. Let's say that again, p will contain the address in memory of num.

Now one thing about pointers is that, logically, they contain two values.
  • p is the location holding the address in memory of num.
  • *p is the location pointed to by that address.

So if we use p we can manipulate WHERE in memory the pointer is pointing to. Yet if we use *p we can manipulate the data contained within the address that the pointer is poining to. If we alter *p, we also alter the variable it points to, let's look at an example. p contains the pointed-to address, *p is another name for the variable it is pointing to. Get it? I hope so, it's kind of confusing at first.

Think of *p as an alias for the variable it points to, it allows you to manipulate the data within that variable. While p controls which variable, which address in memory we are pointing to. Pointers allow us to jump around memory addresses and manipulate the data in them, allowing us to get into a lower-level, into the workings of things. To fully understand we should discuss memory addresses.

Memory Addresses

All computers have memory, also called RAM. RAM holds the programs your computer is currently running, along with the data the programs are currently manipulating. Each byte of memory has it's own address, the address of the first byte is 0, followed by 1, 2, 3... etc. Memory can group bytes together if it needs to form a larger variable, this happens when we declare an int variable.

An int variable is assigned four consecutive bytes in memory. When the program runs, the computer reserves space for that variable somewhere in memory, and from here on the data in the variable can be accessed by the computer by the address at which it is located.

Consider the following:

Do you see? Now the computer knows that the data for number is stored in four consecutive memory addresses starting at 220, 126. Now if we declare a pointer and do:

int *pointer = &number;

Memory could now look something like this:

The value we assigned to number is stored in its area in memory, and the pointer also has it's own place in memory. The thing about the pointer is that the data it contains is the address in memory of the variable to which is "points". If we change the value stored in the pointer, we change where it points. One thing i must mention, most computers today use 32-bit (4 byte) memory addresses. So the pointer is assigned 4 bytes of memory. Some computers use 64-bit memory addressing, meaning pointers on that computer would take up 8 bytes in memory.

But, why use them?

I asked the same question, it seems pointless, and in the above examples i suppose it is. I'm not showing you why pointers are used, i'm trying to explain how they're used, and to help you understand how they work. The advantages are pretty unclear, but as you progress and learn more about different data types you will realise the advantages. You can quickly change something with a pointer rather than changing much more data. It's just an easy way to work at the memory address level, manipulate data contained there, it allows you to manipulate data in memory more accurately. Make good use of pointers, they make C programs much more efficient.

Control Structures and Conditionals

There are a few control structures in C that you can make use of, very similar in syntax to those in Perl and PHP.


These allow you to execute code IF a boolean expression is true:

This speaks for itself really. If 1 is equal to 1, print out so, if not, print out that it isn't. Obviously 1 will always be equal to 1, so the printf() statement between the curly braces after the if() function will be executed.

If 1 wasn't equal to 1, then the else would be executed.

It's pretty easy to see what's going on here, these functions allow is to test if a boolen expression, or series of boolean expressions are true, and execute code depending on those tests.

Boolen Expressions

Any expression that returns TRUE will cause a conditional statement to execute the code contained within its brackets. The computer sees a boolean expression as either true or false. 0 is false, and anything else is true.


The while function is a loop, while the expression is true it will continue to execute the code in its brackets.

This simply means, while the expression is true, execute the code between the curly brackets. The while function checks the expression, if it's true it executes the code then jumps back and tests the expression again, looping until it checks and finds the expression is false, then it continues executing any code after the while() function. In the example above it keeps checking and adding one to a each time, when a reaches 10, it is no longer less than 10, as stated in the expression, so it will discontinue its loop. So the example will print out the numbers 0 to 9.

We can also do:

Which is the same thing, do the code between the curly braces while the expression in the while() statement is true. If the statement is never true, the code in the braces will not be executed at all. Remember when checking for equality in a boolean expression, don't confuse a = b with a == b. = is the operator we use to assign a value to a variable, so if we use a single = it will assign b to a and then check whether a is true or not (effectively checking if b is true).


We could do the same as we did in the while() examples with for(). For() allows us to include everything in one line.

This is neater, it allows us to initialise the variable with a value, then test the expression, then perform an action on the variable. The code will execute while the expression is true, and if it is true, it performs the action and then executes the code between the braces. So we initialise a at zero, test if it's les than 10, if it is increment it, print out the value in a, and then go back and check the expression again, until it's no longer true. For() allows more:

Seperating them with commas, we can include multiple initialisation variables and perform multiple actions, we cannot use a comma in the boolen expression, although we can test multiple conditions by using the AND (&&) sign. This will initialise both variables at zero, check to see whether a is less than 10 AND b is less than 20, while this expression is true execute. When the expression is false discontinue the loop, effectively counting from 0 - 9 with a, and counting up in two's with b.

Remember, although you initialise the variables with a value in for(), you still have to declare them first. Have a play around with these functions, get used to them, and when you're ready read on...


In this chapter we're going to use a new variable arrangement called an array. An array lets you declare and work with many variables of the same type. Say we wanted four integers:

int a, b, c, d;

Pretty easy, but what if we wanted 500? An easier way to do this is:

int a[4];

This is an array. The four integers inside the array are accessed with an index, it works like so:

Remember, although we define the array with four items, the index starts at 0. So the last item in the array is accessed with an index value one lower than the number of items in the array.

We can loop through the items in an array, the following code initialises all the values in the array as 1:

Remember the for() loop from the last chapter? It loops through while i is less than 6, incrementing i each time and assigning 1 to each item in the array, i represents the incrementing array index. C has no range checking, so if you index past the end of an array you will be manipulating memory beyond the range of that array, effectively overwriting data in memory that you shouldn't be. This will cause a crash or garbled data.

Compared to a normal variable.

Array "a" index
1 a[0]
1 a[1]
1 a[2]
1 a[3]
1 a[4]
1 a[5]

variable "b" index
1 b

You would change the value in the array with something like a[3] = 5; yet for the variable, simply b = 5;. An array takes up consecutive addresses in memory, it is an array of variables.

You will see more of arrays as you progress, it's hard to understand many concepts until you see the advantages when you actually use them.

Pointers and Arrays

Arrays and pointers are closely linked in C. To use arrays effectively it's a good idea to know how to use pointers with them. Let's have a look at an example:

Compile this program and run it.

It won't run, why? Because you can't assign a to b. You have to use something like this:

The line #define MAX 10 is a simple constant. We haven't seen this before so i should mention it. All it is in a CONSTANT value we can use throughout the program. MAX is a variable that holds the value of 10, only we cannot modify it, it's constant. Constants are normally typed in upper-case to make it obvious to anyone reading the program that it is a constant.

a and b are unusual in C in that they're not techinically arrays themselves. They are permanent pointers. What does that mean? Well, a POINTS to the first item in its array, and b POINTS to the first item in it's array, they are pointers, only they cannot be changed to point to something else. They hold the addresses of a[0] and b[0]. Therefore a = b; is illegal.

The code above is legal. p = a; works because a is techically a pointer, so assigning a to p makes p contain the address of the first element of of the array a[]. So now *p points to a.

Remember, a is a pointer, it points to address of the first element in the array, and always points there. &a[0]; is the address of the same item in the array, so they are the same.

Now that we have assigned the address of a[]'s first element to p, we can use the pointer to move around the array, consider the below:

This will output:

pointer is pointing to the value 5
pointer is now pointing to the value 7

Do you see? We can use the pointer to jump through the array elements. If we increment p then the pointer will jump the appropriate number of bytes to the next array item. C takes care of the issue of element size, so adding one will jump to the next element, adding two will jump to the element after the next element... etc.

Text files in C

In this chapter we're going to cover how we read from and write to text files using C. We will cover a few new functions:

  • fopen - Opens a text file.
  • fclose - Closes a text file.
  • feo - Detects end-of-file marker in a file.
  • fprintf - Prints formatted output to a file.
  • fscanf - Reads formatted input from a file.
  • fputs - Prints a string to a file.
  • fgets - Reads a string from a file.
  • fputc - Prints a character to a file.
  • fgetc - Reads a character from a file
  • .

All these functions are in < stdio.h > , so we only need to include that header file for any of these functions to work. Saying that, when working with text files we'll have to manipulate strings, functions for working with strings are contained within . These functions are very easy to use.

f = fopen("filename", "mode");

We use fopen() to open a file. This function requires two parameters, the first is the name of the file we wish to open, and the second is the "mode" we want to use to open this file. The three main modes are "r", "w" and "a" -- read, write and append.

The function returns a file pointer we can then use to access the file, in this case f.

Firstly we declare a pointer to use with the file operations, declaring it as type "FILE" tells C this pointer will be used with a file. We then define our integer to use in the program.

f = fopen("file.txt", "w");

This line opens a file named "file.txt" for writing (w). "w" is a destructive write mode, meaning if the file doesn't exist already, it is created; if it already exists it is destroyed and a blank copy put in it's place for the program to use. The file is opened and assigned to the pointer.

Now we test if the file opening was successful. If f is not true, return an error from main(), halting and exiting the program, as we can't open the file, there's no point going on.

Now we use a for() loop to initialise our variable at 1 and loop through over and over until the value is no longer less than 11 (or until it reaches 10). The fprinf() function should look familiar. It's similar to printf() only it has an extra parameter before the parameter that contains what we wish to print. This parameter contains the pointer to the file we wish to print to.

return 0;

We then close the file using fclose() and finish the program.

Reading From a File

To read a file, open it with "r" mode. Now this is the first time we've used strings with C. Previously we have only used integers and single characters. To work with strings in C we store them in an array.

Compile that and run it, make a file named "file.txt" in the same directory as the executable and write a few lines to it. The run the executable and observe, it prints out the lines in the file to the screen.

char string[1000];

In this line we declare an array named "string" that has 1000 items. It is an array of char variables, we use this to extract the data from the file in string form.

This is the code that does the work. Let's slow down, look at this and ensure we fully understand it.

Remember the while() function? While a condition is true, execute the code between the curly brackets.

fgets(string, 1000, f)

This is the new part, we are using the fgets() function, which as said above, reads a string from a file. The first parameter is our array, in which we want to put a line from the file. The second is the maximum number of characters we allow our program to read for each line, it's unlikely a line will be more than 1000 characters long. The last parameter is the file pointer, f.

When we use fgets() we read one line of the file into our array. If we put this in a while() function, it keeps looping over and over, reading each line in, while there are more lines to read in the file, it will keep looping, until it reads in each line of the file one by one, using printf() to print each line out. This happens so fast it looks as if the program read the entire file.

Observe in the printf() function. We didn't include a newline (n) character after we print out our array, this is because fgets reads the line in complete with its newline character, so we don't need to add one. We also used to %s sign to signify we are dealing with string output.

Remember, programming isn't hard, it's logic -- everyone can solve logic. It's learning a programming language that takes time and practice. You have to sit and practice, and write these programs out until you know the functions, and know what they do. Soon you will be thinking up your own programs, stick with it.


C allows you to create your own functions. Functions accept parameters and return a result. They let us simplify our programs into sections that can be called by other sections. Let's have a look at a simple example:

Now remember we said a functions returns a value. We put void because our function doesn't. if we expected it to return an int value, we put int. if a char, we put char, etc. We then declare the name of the function and the code to be executed goes between the curly braces.


Is how we call the function, we must use the () in the call to tell the compiler we're calling a function. Our program uses no parameters and returns no result, it is a very simple function. But it shows you the structure and how to declare one. We could now use this in a program.

Functions allow us to break up the program, if we wanted to print out the info about our program over and over in differen parts of a program, it's easier to use a function and just call it.

Returning a Value

We can return values from a function, take a look below:

Now our function returns a result, it returns an integer. We add 2 and 3 together, assign the result to the_sum and then return it.

So we define the return type as int:

int our_sum()

Then we write the function that adds to numbers together. Then we open the main() function of our program and assign the result returned from our function to a variable:

sum = our_sum();

That's returning a result, the result the function returned was assigned to sum.


We can pass parameters to a function and use them within that function. This is how we do it.

Instead of () being empty this time, we define our parameters. We expect two parameters to be passed to this function, which we call a and b We can then return a value, we return the value of a added to b. So we could do:

When we call sum = our_sum(2, 3); we pass two values to the function, 2 and 3. The function then handles these as a and b, we add them together and return the result, which we then assign to sum and print out.

Old Style

Sometimes you may see functions written in the old style. C has evolved over the years but it's important to see what the old style looks like incase you ever read code that uses it, here's our function in old style.

It is the same as our function, it executes exactly the same, i just thought you should see it incase you ever come across it.


To conclude the functions sestion we're going to write a little program. Now we have covered quite a few concepts we can put them together.

Let's write a program that let's the user enter three names (maximum 30 chars) and three ages, then print out the combined ages of the people and write the info to a text file named "data.txt". Pretty simple but it will allow us to put a few things together.

There we have it, i'm not going to go through and explain the code. If you've been reading the chapters properly you'll be well aware of how that works. It isn't difficult, and it's kind of pointless, though things are getting a little more interesting.

Let's go on and discuss pointers with functions.

Functions and Pointers

We can use pointers when passing parameters to functions. Remember how when we use scanf() we must type the '&' sign before the variable? This is because scanf() uses pointers, if you don't pass the parameter as a memory location it crashes.

Consider this program that swaps two numbers around.

Run it, it doesn't work. Normally with functions we define our own variables within the function and then return the values into variables in the main function. We don't have to do that, we can use pointers to directly access the address in memory of our variables. Remember, a pointer points to the address in memory of a variable, it points to the data stored for that variable. Consider the below code:

Notice we're using pointers now. Let's go through what happens.

In our main function we define our variables and give them a value. We then call swap_nums(), only this time we pass (&a, &b). We're passing the function the addresses in memory of the variables a and b, not their actual value.

Now we define our pointers for our function. Remember, we passed the function our variable's addresses, so it makes sense we use pointers that now point to our variables. We then do the swap:

Let's go through this and explain it step-by-step:

int extra;

Define an integer named extra.

extra = *a;

Pass the value pointed to by *a to our variable. So now extra contains the value of a from the main() function. The *a in our function is a pointer, we use it to directly access the memory and load the value of a into extra. We assigned 5 to a, so now extra contains 5.

*a = *b;

Load the value pointed to by *b (7) into *a, so now *a contains the value we assigned to b in our main() function, a contains 7.

*b = extra;

Load the value in extra (5) into the variable pointed to by *b. B points the the address in memory of b from the main() function so we are infact loading 5 into b.

The values have been swapped, we used pointers to access the memory addresses of the variables and manipulate the data contained within them. This is an example of the power of pointers, they allow you to work at a "lower" level.

So when you're using scanf() and you have to do scanf("%d", &num);, this is why, the scanf() function wants the address in memory of the variable so it can laod the data into it, you must give it the address in memory or your code will crash. Now you know why you need to do this, and hopefully that example explained pointers a little more to you. Pointers are used extensively in C, they make code more efficient, learn to use them.


That concludes our introduction to C programming. I've tried to cover the basics of C. The difficult part of programming is getting started, hopefully this tutorial did that for you, you can put together the information you have learned here and think up your own ideas. Search the internet for information you need, learn how to use C to its maximum potential -- stick with it and you will.

1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  10  |  
Next »

No Comments for this page.

You Must be logged in or a member to comment.

Tutorial Stats

Tutorial Stats

0 Total Comments
3.33 Rating of 5 (3 Votes)


Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article



· Beginning Visual C++ 6.0
Your Article Here

"" Copyright © 2002-2018; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank