Sunday 20 November 2011

What is iterative processing? in C programming

What is iterative processing?

Iterative processing involves executing the same programming statements repetitively, possibly breaking at a point when a condition occurs. The C language provides some built-in constructs for iterative processing, such as while loops, do...while loops, and for loops. With each of these, a predefined number of statements is executed repetitively while a certain condition remains true. Here is an example of iterative processing:

while (x < 100)
{
y = 0;
do {
for(z=0; z<100; z++)
y++;
} while (y < 1000);
x++;
}

In this example, the statements included in the while loop are executed 100 times. Within the while loop is a do...while loop. In the do...while loop is a for loop that is executed 10 times. Within the for loop, the variable y is incremented 100 times. Therefore, the statement

y++;

is executed 100,000 times (100 whiles ´ 10 do...whiles ´ 100 fors). y will not be 100,000 when the while loop is complete, however, because y is reset to 0 each 1000 iterations.

Iterative processing is used tremendously throughout C programs. Often, you will use iterative processing to read from and write to arrays and files. For example, here is a program that uses iterative processing to read
in your AUTOEXEC.BAT file and print its contents on-screen:

#include <stdio.h>
#include <stdlib.h>
int main(void);
int main(void)
{
FILE* autoexec_file;
char buffer[250];
if ((autoexec_file = fopen(“C:\\AUTOEXEC.BAT”, “rt”)) == NULL)
{
fprintf(stderr, “Cannot open AUTOEXEC.BAT file.\n”);
exit(1);
}
printf(“Contents of AUTOEXEC.BAT file:\n\n”);
while (!feof(autoexec_file))
{
fgets(buffer, 200, autoexec_file);
printf(“%s”, buffer);
}
fclose(autoexec_file);
return(0);
}

Notice that this example uses a while statement to repeatedly call the fgets() and printf() functions to read in lines from the AUTOEXEC.BAT file and print them to the screen. This is just one example of how iterative processing can be used.

Cross Reference:

XIX.12: What is recursion, and how do you use it?

No comments:

Post a Comment