Topic : Introduction to C Programming
Author : Mkoubaa
Page : 1 Next >>
Go to page :


Introduction to C Programming
Part 1: Introduction


C is an easy language to learn, especially if you already know Pascal or some other procedural language. Every concept in Pascal maps directly to a concept in C: The ideas are exactly the same, but you use different words to express them. C sometimes seems difficult because it gives the programmer more freedom, and therefore makes it easier to make mistakes or create bugs that are hard to track down.
These tutorials introduce you to C by showing you how Pascal maps to it. It also introduces several concepts not found in Pascal. Most of these new concepts deal with pointers. Readers coming from a Fortran, Cobol, BASIC, etc. background should find that the Pascal code is easy to read.
I believe that the only way to learn C (or any language) is to write and read a lot of code in it. One very good way to get C programming experience is to take existing programs that you have already written and convert them. This way, if the program does not work in C, you know that the translation is causing the problem and not the original code.
One major difference between Pascal and C causes problems: C does not allow nested procedures, so you must remove any in order to convert Pascal programs. You should avoid nested procedures in your Pascal programs altogether or remove nesting from programs in the Pascal version. That way, you can retest the program in the Pascal environment before you move it over to C.
Also watch case sensitivity in C. C compilers consider uppercase and lowercase characters to be different: XXX, xxx, and Xxx are three different names in C. By convention, constants in C are spelled with uppercase, while variables are spelled with lowercase, or an uppercase/lowercase combination. C Keywords are always lowercase.
In this tutorial, all compilation instructions and references to man pages assume that you are working on a fairly normal UNIX workstation. If you are not, you will have to use the manuals/help files for your system to map the instructions to your environment.
In the next tutorial we will start with an extremely simple C program and build up from there.
Introduction to C Programming

Part 2: A Simple Factorial Program


Below is a very simple C program that finds the factorial of 6. Fire up your favorite editor and enter it. Do not copy the file or cut and paste: Actually type the code, because the act of typing will cause it to start entering your brain. Then save the program to a file named samp.c. If you leave off .c, you will get a ``Bad Magic Number'' error when you compile it, so make sure you remember it.

/* Program to find factorial of 6 */
#include <stdio.h>

#define VALUE 6

int i,j;
void main()  
{    
    j=1;    
    for (i=1; i<=VALUE; i++)      
        j=j*i;    
    printf("The factorial of %d is %d\n",VALUE,j);  
}


When you enter this program, position #include and #define so that the pound sign is in column 1. Otherwise, the spacing and indentation can be any way you like it. On most UNIX systems, you will find a program called cb, the C Beautifier, which will format code for you.
To compile this code, type cc samp.c. To run it, type a.out. If it does not compile or does not run correctly, edit it again and see where you went wrong.
Now let's look at the equivalent Pascal code:

{ Program to find factorial of 6 }
program samp;
const    
    value=6;  
var    
    i,j:integer;  
begin    
    j:=1;    
    for i:=1 to value do      
        j:=j*i;    
    writeln('The factorial of ',value,' is ',j);  
end.


You can see an almost one-to-one correspondence. The only real difference is that the C code starts with #include <stdio.h> . This line includes the standard I/O library into your program so that you can read and write values, handle text files, and so on. C has a large number of standard libraries like stdio, including string, time and math libraries.
The #define line creates a constant. Two global variables are declared using the int i,j; line. Other common variable types are float (for real numbers) and char (for characters), both of which you can declare in the same way as int.
The line main() declares the main function. Every C program must have a function named main somewhere in the code. In C, { and } replace Pascal's begin and end . Also, = replaces Pascal's := assignment operator. The for loop and the printf statement are slightly strange, but they perform the same function as their Pascal counterparts. Note that C uses double quotes instead of single quotes for strings.
The printf statement in C is easier to use than the Pascal version once you get used to it. The portion in quotes is called the format string and describes how the data is to be formatted when printed. The format string contains string literals such as The factorial of and \n for carriage returns, and operators as placeholders for variables. The two operators in the format string indicate that integer values found later in the parameter list are to be placed into the string at these points. Other operators include for floating point values, for characters, and for strings. You can type man printf to get the man page on formatting options.
In the printf statement, it is extremely important that the number of operators in the format string corresponds exactly with the number and type of the variables following it. For example, if the format string contains the operators and it must be followed by exactly three parameters, and they must have the same types in the same order as those specified by the operators.
This program is good, but it would be better if it read in the value instead of using a constant. Edit the file, remove the VALUE constant, and declare a variable value instead as a global integer (changing all references to lower-case because value is now a variable). Then place the following two lines at the beginning of the program:

printf("Enter the value:");  
scanf("%d",&value);


The equivalent code for this in Pascal is:

write('Enter a value:');  
readln(value);


Make the changes, then compile and run the program to make sure it works. Note that scanf uses the same sort of format string as printf (type man scanf for more info). Also note the & sign in front of value. This is the address operator in C: It returns the address of the variable, and it will not make sense until we discuss pointers. You must use the & operator in scanf on any variable of type char, int, or float, as well as record types, which we will get to later. If you leave out the & operator, you will get a segmentation fault when you run the program.
C errors to avoid:
Forgetting to use the & in scanf.
Too many or too few parameters following the format statement in printf or scanf.
Forgetting the */ at the end of a comment.

Introduction to C Programming
Part 3: Branching and Looping


If statements and while loops in C both rely on the idea of Boolean expressions, as they do in Pascal. In C, however, there is no Boolean type: You use plain integers instead. The integer value 0 in C is false, while any other integer value is true.
Here is a simple translation from Pascal to C. First, the Pascal code:

if (x=y) and (j>k) then    
    z:=1  
else    
    q:=10;


The C translation looks very similar, but there are some important differences, which we will discuss next.

if ((x==y) && (j>k))    
    z=1;  
else    
    q=10;


Notice that = in Pascal became == in C. This is a very important difference, because C will accept a single = when you compile, but will behave differently when you run the program. The and in Pascal becomes && in C. Also note that z=1; in C has a semicolon, that C drops the then, and that the Boolean expression must be completely surrounded by parentheses.
The following chart shows the translation of all boolean operators from Pascal to C:

Pascal C
=      ==
<      <
>      >
<=     <=
>=     >=
<>     !=
and

Page : 1 Next >>