Tuesday, January 13, 2009

Basic Structure of a Program : Iteration

Iteration

The last important construct is itteration. It executes a set of programming statements several times until certain condition is reached. The sentinel condition is usually evaluated by using pre increment and post increment Operation. Lets have a look at the example bellow. It shows the post increment operation in a simple sequential program :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int i = 10;
system("clear");
printf("%d", i++); /*The output of this operation is 10, since the variable is used first and then the value is incremented */
}

Now we are going to have a pre increment operation :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int i = 10;
system("clear");
printf("%d", ++i); /*The output of this operation is 11, since the variable is incremented first and then the value is displayed */
}

Now lets use this operation for controlling a for loop. Example below is post increment :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int j;
system("clear");
for (j=0;j<10;)
{
printf("%d \n", j++);
}
}

The output of the program is : 0 1 2 3 4 5 6 7 8 9. What would happened if the sentinel is pre increment
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int j;
system("clear");
for (j=0;j<10;)
{
printf("%d \n", ++j);
}
}
The output will decidedly different : 1 2 3 4 5 6 7 8 9 10.

Now its time for use to move to the nitty gritty of C programming.