The for Loop in C
The for statement is a C programming construct that executes a block of one or more statements a certain number of times. It is sometimes called the for loop because program execution typically loops through the statement more than once. You’ve seen a few for statements used in programming examples earlier in this book. Now you’re ready to see how the for statement works.
Structure for loop in C
initial, condition, and increment are all C expressions, and statement is a single or compound C statement. When a for statement is encountered during program execution, the following events occur:
for loop syntex in C
initial is any valid C expression. It is usually an assignment statement that sets a variable to a particular value. condition is any valid C expression. It is usually a relational expression.
//Syntex
for ( initial; condition; increment )
statement;
Example for loop-1
/* Prints the value of x as it counts from 0 to 9 */
int x;
for (x = 0; x <10; x++)
printf( “\nThe value of x is %d”, x );
Example for loop -2
/*Obtains values from the user until 99 is entered */
int nbr = 0;
for ( ; nbr != 99; )
scanf( “%d”, &nbr );
Example for loop – 3
/* Lets user enter up to 10 integer values */
/* Values are stored in an array named value. If 99 is */
/* entered, the loop stops*/
int value[10];
int ctr,nbr=0;
for (ctr = 0;ctr < 10 && nbr != 99; ctr++) {
puts(“Enter a number, 99 to quit “);
scanf(“%d”, &nbr);
value[ctr] = nbr;
}