17. Use The For Loop

The for loop is one of C's three statements. It allows one or more statements to be repeated. The for  loop is considered by many C programmers to be its mast flexible loop. The for loop is used to repeat a statement or block of statements a specified number of tims. It's general form repeating a single statement is shown here.



for(initialization;conditionl-test;increnent or descrement)
statement;



The initialization scction is used to give an initial value to the variable that controls the loop. This varible is usually referred to as the loop-control. The initialization section is executed only before the loop be gins. Then execute the conditional-test. If the condition true then the program execute the statement. When the statement is end then the program come back in the increment statement. After increment test the condition if the condition is true then the program executed the statement. It will be continue. When the condition will be wrong the for loop is end.



Example:
As a simple first example. This program use a for loop to print the numbers 1 through 10 on the screen.

#include<stdio.h>
void main()
{
int num;
for(num=1; num<11; num=num+1)
printf("%d",num);
printf("terminating");
getch();
}

This program produces the following output:
1 2 3 4 5 6 7 8 9 10 treminating.
The program works works like this :
First, the loop control variable num is initialixed to 1. Next, the cxpession num<11 is evaluated. Since it is true, the for loop begins running, After the number is printed, num is incremented by one and the conditional test is evaluated again. This provcess continues until num equals 11. When this happens the for loop stops, and terminating is displayed, keep is mind that the initialixation portion of the for loop is only excecuted once, when the loop is first entered.
Post by Anrob. 


No comments:

Post a Comment

free counters