1.

Explain the working of ‘for’ loop structure.

Answer»

A ‘for’ loop is a repetition control structure, that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

The syntax of a ‘for’ loop in C++ is:

for (initialization; condition; increment/decrement)

statement(s);

}

The working of a ‘for’ loop:

1. The initialization step is executed first, and only once in the beginning. It is used to declare and initialize loop control variables.

2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’ loop.

3. After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment/ decrement statement and update any ‘loop’ control variables.

4. Then the condition is evaluated again. If it is true, the ‘ loop’ executes and the process repeats itself (body of ‘loop’, then increment step, and then again condition). After the condition becomes false, the ‘for’ loop terminates.

Example:

#include<iosteam>

int main()

{

//for loop execution

for(int a = 10; a <20; a = 1+ 1)

{

cout<<"value of a:"<<a<<end1;

}

return 0;

}

When the above code is compiled and executed, it produces following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15



Discussion

No Comment Found