Home | Computer | For Loop in C++ | Syntax of for loop in C++

For Loop in C++ | Syntax of for loop in C++

August 24, 2022

For loop executes one or more statements a number of times. This loop is also called a counter-controlled loop. It is the most flexible loop. That is why most programmers use this loop in programs.

Syntax of for loop

image showing the syntax of for loop

Initialization:   It specifies the starting value of a counter variable. One or many variables can be initialized in the initialization phase. To initialize many variables, each variable is separated by commas.

Condition:  The condition is given as a relational expression. When the condition is true the statement is executed just at that time. When the condition is false the statement is never executed.

Increment/ decrement:  This part of the loop specifies the change in the counter variable after each execution of the loop. To change many variables, each variable must be separated by a comma.

Statement:  Statement is the instruction that is executed when the condition is true. If two or more statements are used, these are given in the braces {}. It is called the body of the loop.

for loop have three expressions which are separated by semicolons. Two statements (initialization and increment/ decrement expressions) are optional.

Working of for loop

The number of cycles depends on the initialization, condition, and increase/ decrement parts. The initialization portion is executed as it were once when the control enters the circle. After initialization, the given condition is assessed. 

On the off chance that it is genuine, the control enters the body the of circle and executes all articulations in it. At that point, the increment/decrement portion is executed that changes the esteem of a counter variable. The control again moves to the condition part. This process continues while the condition remains true. The loop is terminated when the condition becomes false.

Flowchart of for loop

image showing the flowchart of for loop

Example

#include <iostream.h>

#include <conio.h>

Void main()

{

int n;

clrscr ();

for(n=1; n<=5; n++)

cout<<n<<endl;

getch();

}

while (n <= 5)

{

Output

1

2

3

4

5