Tutorial 6.3: for Repetition Structure

for Loop Statement
Unlike while and do while statement, for statement handles all the details such as variable initialisation, variable update and loop condition within single parantheses. If you still confuse with what i mean, lets revise the while loop example.



As you can see, the statements to control the loop operation are separated. In the for statement, these statements are combined together. Lets look at the for statement structure to have better understanding.

for ( variable initialisation; loop condition; variable update ) {
...statements...
}


for statement structure has three (3) fields which are variable initialisation, loop condition and variable update. These fields in the for statement are optional. we may omit variable initialisation and place it elsewhere in the program for example before for statement. If loop condition is omitted, C will assume that the condition is true thus resulting an indefinite loop. Variable update may be ommited if we want to place it in the body of for statement.

An example of for statement is given. The purpose of this program is to display zero (0) to nine (9).
#include <stdio.h>

int main()
{
 int count = 0;
 for(count = 0; count < 10; ++count) {
  printf("%d\n", count);
 }
 return 0;
}
Sample output:

0
1
2
3
4
5
6
7
8
9

Explanation:

As usual, we declare an integer variable count which acts as the loop counter. We do not initialise the variable unlike while and do while statement because it will be taken care of in the for statement.
for(count = 0; count < 10; ++count) {
 printf("%d\n", count);
}
Here we have the for repetition structure. The operation of the loop is controlled by the three expression between the for statement parantheses. In the variable initialisation field, we initialise variable to 0. The specified loop condition is count less than 10

Next: Nested Loop

1 comment:

yentildaggs said...

MgBET launches New Playtech casino in India | JTM Hub
MgBET, a global gaming 원주 출장샵 provider, is expanding its 경상남도 출장샵 international footprint 서울특별 출장마사지 by expanding 김해 출장안마 its European footprint by launching a new 공주 출장마사지 Playtech

Post a Comment