Looping Statements in C Language
Loop Statements in C are used to execute and repeat a block of statements depending on the value of a condition. There are three types of Loop Control Statements in C language:
1. for loop
2. while loop
3. do-while loop
for loop:
The for loop is an entry-controlled loop that provides a more concise loop control structure. A for loop is used to execute and repeat a block of statements depending on a condition. It has the following syntax:
for(;;) { - - - - - - - - - - - - - - - - - - - - }
Nested for loop:
This statement block of a for loop lies completely inside the block of another for loop that is called Nested for loop or Nested for Statement.
for(i=1;i<=3;i++) { - - - - - - - - for(j=1;j<=5;j++) { - - - - - - - - - - - - - - - - } }
while loop:
It is also an entry-controlled loop statement. A while loop is used to execute and repeat a block of statements depending on a condition. It has the following syntax:
while() { - - - - - - - - - - - - - - - - }
do-while:
A do-while loop is an exit-controlled loop statement. It is used to execute and repeat a block of statements depending on a condition. It has the following syntax:
do { - - - - - - - - - - - - - - - - } while()
We can Compare Between for loop while loop and the do-while loop below:
for loop vs while loop vs do-while loop:
1. A for loop is used to execute and repeat a statement block depending on a condition which is evaluated at the beginning of the loop. | 1. A while loop is used to execute and repeat a statement block depending on a condition which is evaluated at the beginning of the loop. | 1. A do-while loop is used to execute and repeat a statement block depending on a condition which is evaluated at the end of the loop. |
2. A variable value is initialized at the beginning of the loop. | 2. A variable value is initialized at the beginning or before of the loop. | 2. A variable value is initialized before the loop or assigned inside the loop. |
3. The statement block will not be executed when the value of the condition is false. | 3. The statement block will not be executed when the value of the condition is false. | 3. The statement block will not be executed when the value of the condition is false, but the block is executed at least once irrespective of the value of the condition. |
4. A statement to change the value of the condition or to increment the value of the variable is given at the beginning of the loop. | 4. A statement to change the value of the condition or to increment the value of the variable is given inside of the loop. | 4. A statement to change the value of the condition or to increment the value of the variable is given inside of the loop. |
5. A for loop is commonly used by many programmers. | 5. A while loop is widely used by many programmers. | 5. A do-while loop is used in some cases where the condition need to be checked at the end of the loop. |