It is often the case in programming that you want to do something a fixed number of times. Perhaps you want to calculate the paychecks for 120 employees or print out the squares of all the numbers from 1 to 50. The for loop is ideally suited for such cases.
Let's look at a simple example of a for loop which will print numbers from 0 to 9:
included files
void main()
{
int count;
clrscr();
for(count=0;count<10;count++)
printf("Count=%d\n",count);
getch();
}
The output will be:
Count=0
Count=1
Count=2
Count=3
Count=4
Count=5
Count=6
Count=7
Count=8
Count=9
This program's role in life is to execute a printf() statement 10 times.
Structure of the for Loop:
The loop expression is divided by semicolons into three separate expressions: the "initialize expression", the "test expression", and the "increment expression".
==================================================
Expression Name Purpose
==================================================
count=0 Initialize expression Initializes loop variable
count<10 Test expression Tests loop variable
count++ Icrement expression Increments loop variable
---------------------------------------------------------------------------------------------
The Body of the Loop:
Following the keywords for and the loop expression is the body of the loop: that is, the statement (or statements) that will executed each time round the loop. In our above example, there is only one statement:
printf("Count=%d\n",count);
Note that this statement is terminated with a semicolon, wheras the for with the loop expression is not.
If you have any questions, you can ask me freely!
Let's look at a simple example of a for loop which will print numbers from 0 to 9:
included files
void main()
{
int count;
clrscr();
for(count=0;count<10;count++)
printf("Count=%d\n",count);
getch();
}
The output will be:
Count=0
Count=1
Count=2
Count=3
Count=4
Count=5
Count=6
Count=7
Count=8
Count=9
This program's role in life is to execute a printf() statement 10 times.
Structure of the for Loop:
The loop expression is divided by semicolons into three separate expressions: the "initialize expression", the "test expression", and the "increment expression".
==================================================
Expression Name Purpose
==================================================
count=0 Initialize expression Initializes loop variable
count<10 Test expression Tests loop variable
count++ Icrement expression Increments loop variable
---------------------------------------------------------------------------------------------
The Body of the Loop:
Following the keywords for and the loop expression is the body of the loop: that is, the statement (or statements) that will executed each time round the loop. In our above example, there is only one statement:
printf("Count=%d\n",count);
Note that this statement is terminated with a semicolon, wheras the for with the loop expression is not.
If you have any questions, you can ask me freely!
0 comments:
Post a Comment