for Loop in C Programming Language

Notes:

Looping / Iterative Statements in C:
- execute set of statements repeatedly
- to execute one or more statements repeatedly, we take help of looping or iterative statements.
- for loop
- while loop
- do while loop

for loop: Entry control loop
- Computer executes body of the for loop, as long as the given conditional expression evaluates to true. If the given conditional expression evaluates to false then it terminates the loop.

Syntax:
for(initialization; conditional expression; increment/decrement) // head of the for loop
{
statement(s); // body of the for loop
}

where:
Initialization part:
- is a place where we initialize one or more counter variables
Conditional expression part:
- is a place where we write a conditional expression, which determines whether the body of the for loop is executed or terminated
Increment / decrement part:
- is a place where we increment or decrement initialized counter variables

Ex: Program to display Hello World 5 times using for loop
int counter=0;
for(counter=0; counter<5; counter++ ) // head of the for loop
{
printf("Hello World\n"); // body of the for loop
}

Note:
- Head of the for loop must be handled carefully so that it does not enter into an infinite loop
- Initialization, conditional expression, increment or decrement parts are optional
- If no statement is written in the head of the loop then it is considered as an infinite loop

Ex 1:
int counter=0
for( ; counter<5; counter++ )
{
printf("Hello World\n");
}

Ex 2:
int counter=0
for( ; counter<5; )
{
printf("Hello World\n");
counter++;
}

Ex 3:
for( ; ; )
{
printf("Hello World\n");
}

Note:
- When we know exactly how many # of times the body of the loop is executed, we use for loop.