Topic : Introduction to C Programming
Author : Mkoubaa
Page : << Previous 2  Next >>
Go to page :


   &&
or     ||
not    !

The == sign is a problem because every now and then you may forget and type just =. Because integers replace Booleans, the following is legal in C:

void main()  
{    
    int a;
    
    printf("Enter a number:");    
    scanf("%d",a);    
    if (a)    
    {      
        blah blah blah    
    }  
}


if a is anything other than 0, the code that blah blah blah represents gets executed. Suppose you take the following Pascal statement:

if a=b then

and incorrectly translate it to C as:

if (a=b)  /* it SHOULD be "if (a==b)" */

In C, this statement means "Assign b to a, and then test a for its Boolean value." So if a becomes 0, the if statement is false; otherwise, it is true. The value of a changes as well. This is not the intended behavior (although this feature is useful when used correctly), so be careful with your = and == conversions.
While statements are just as eay to translate. For example, the following Pascal code:

while a < b do  
begin    
    blah blah blah  
end;

in C becomes:

while (a < b)  
{    
    blah blah blah  
}


C also provides a "do-while" structure to replace Pascal's "repeat-until," as shown below:

do  
{    
    blah blah blah  
}  
while (a < b);


The for loop in C is somewhat different from a Pascal for loop, because the C version is simply a shorthand way of expressing a while statement. For example, suppose you have the following code in C:

x=1;  
while (x<10)  
{    
    blah blah blah    
    x++; /* x++ is the same as saying x=x+1. It's an increment. */  
}


You can convert this into a for loop as follows:

for(x=1; x<10; x++)  
{    
    blah blah blah  
}


Note that the while loop contains an initialization step (x=1 ), a test step (x<10), and an increment step (x++ ). The for loop lets you put all three parts onto one line, but you can put anything into those three parts. For example, suppose you have the following loop:

a=1;  
b=6;  
while (a < b)  
{    
    a++;    
    printf("%d\n",a);  
}


You can place this into a for statement as well:

for (a=1,b=6; a < b; a++,printf("%d\n",a));

It is confusing, but it is possible. The comma operator lets you separate several different statements in the initialization and increment sections of the for loop (but not in the test section). Many C programmers like to pack a lot of information into a single line of C code. I think it makes the code harder to understand, so I break it up.
C Errors to avoid
Putting = when you mean == in an if or while statement.
Accidentally putting a ; at the end of a for loop or if statement, so that the statement has no effect. For example,

for (x=1; x<10; x++);    
    printf("%d\n",x);


only prints out one value because of the semicolon after the for statement.
Introduction to C Programming
Part 4: Arrays and the Bubble Sort

In this section, you will create a small program that generates 10 random numbers and sorts them.
Start an editor and enter the following code:

#include <stdio.h>

#define MAX 10

int a[MAX];
int rand_seed=10;

int rand() /* from K&R - returns random number between 0 and 32767.*/  
{
    rand_seed = rand_seed * 1103515245 +12345;    
    return (unsigned int)(rand_seed / 65536) % 32768;  
}

void main()  
{    
    int i,t,x,y;
  
    /* fill array */    
    for (i=0; i < MAX; i++)    
    {      
        a[i]=rand();      
        printf("%d\n",a[i]);    
    }
  
    /* more stuff will go here in a minute */
}


This code contains several new concepts, although the lines #include and #define should be familiar to you. The line int a[MAX]; shows you how to declare an array of integers in C. As an example, the declaration int a[10]; is declared like this in Pascal:

a:array [0..9] of integer;

All arrays start at index zero and go to n-1 in C. Thus, int a[10]; contains 10 elements, and the largest valid index is 9. Unlike Pascal, C offers no way to change the range of index values. Also note that because of the position of the array a , it is global to the entire program.
The line int rand_seed=10 also declares a global variable, this time named rand_seed. that is initialized to 10 each time the program begins. This value is the starting seed for the random number code that follows. In a real random number generator, the seed should initialize as a random value, such as the system time. Here, the rand function will produce the same values each time you run the program.
The line int rand() is a function declaration. The equivalent function declaration looks like this in Pascal:

function rand:integer;

The rand function accepts no parameters and returns an integer value.
The four lines that follow implement the rand function. We will ignore them for now.
The main function is normal. Four local integers are declared, and the array is filled with 10 random values using a for loop. Note that arrays are indexed exactly as they are in Pascal.
Now add the following code in place of the more stuff ... comment:

/* bubble sort the array */    
for (x=0; x < MAX-1; x++)      
    for (y=0; y < MAX-x-1; y++)        
        if (a[y] > a[y+1])        
        {  
            t=a[y];  
            a[y]=a[y+1];  
            a[y+1]=t;        
        }
/* print sorted array */    
printf("--------------------\n");    
for (i=0; i < MAX; i++)      
printf("%d\n",a[i]);


This code sorts the random values and prints them in sorted order.
Exercises
In the first piece of code, try changing the for loop that fills the array to a single line of code. Make sure that the result is the same as the original code.
Take the bubble sort code out and put it into its own function. (See tutorial 6, if necessary.) The function header will be void bubble_sort. Then move the variables used by the bubble sort to the function as well and make them local there. Because the array is global, you do not need to pass parameters.
Initialize the random number seed to different values.
C Errors to avoid
C has no range checking, so if you index past the end of the array, it will not tell you about it. It will eventually crash or give you garbage data.
A function call must include (even if no parameters are passed. For example, C will accept x=rand;, but the call will not work. The memory address of the rand function will be placed into x. You must say x=rand();.

Introduction to C Programming
Part 5: Details


Operators and Operator Precedence
The operators in C are similar to the operators in Pascal, as shown below:

Pascal C
+      +
-      -
/      /
*      *
div    /
mod    %  

The / operator performs integer division if both operands are integers and floating point division otherwise. For example:

void main()  
{    
    float a;
    a=10/3;    


Page : << Previous 2  Next >>