for loop in c

A for loop (Iteration statement) execute a statement or block of statements until the given condition is true. Including the for loop C language provides two more Iteration statements while and do while.

You can use any one of them for iteration but if you know the number of iteration, then you should use for loop and if you want to break the loop on the basis of the condition, then you should use while loop.

Syntax for loop in C:

for (Expression1; Expression2; Expression3)
{
//for loop body codes
}

In the above mention declaration,

Expression1: It is an initialization expression.

Expression2: It is the controlling expression that is evaluated before each execution of the for loop body.

Expression3: It is evaluated after each execution of the for loop body. Generally, it is an increment statement.

You can check out,

Increment operator in C

Flow Diagram for loop

 

for loop in c

 

Example,

When we compile the above code then we will get below output,

for loop in c

 

How the above program works:

Step 1: Initialize statement will execute first ( loop is initialized).

Step 2: Now controlling statement will execute and verify the condition.

Step 3: If the condition is true, then execute the loop body. If the condition is false then exit from the for loop body.

Step 4: Last step is to increment the value of the loop by 1 and repeat the step2,step3, and step4.

Like another iteration statement, we can terminate for loop using the break, goto, and return keyword. We can also terminate an iteration without exiting the for loop using the continue keyword.

Output:

Value of loop = 0
Value of loop = 1

Statements within the for loop are optional, we can omit these statement according to the requirement. If we remove all the statement then it becomes an infinite loop.

for(;;);  // Infinite loop