For Loop in C++

A for loop is a repetition control structure that allows us to design a loop that will execute a given number of times in an efficient manner. The for-loop statement is quite specific. When we already know how many iterations of that particular piece of code we want to run, we use a for loop. When we don’t know how many iterations to do, we use a while loop, which is covered next.

The syntax of a for loop in C++ programming is as follows.

for (initialise counter; test counter; increment / decrement counter)
{
    //set of statements
}

Here,

  • Initialise counter: This will set the loop counter value to zero. In most cases, i=0.
  • test counter: This is the test condition; if true, the loop continues; otherwise, the loop ends.
  • Counter increment/decrement: Increasing or decreasing the counter.
  • Collection of statements: The body, or executable section, of the for loop, or the set of statements that must be repeated.

One illustration of how a for loop works is shown below.

#include <iostream>
using namespace std;
 
int main()
{
    int num = 10;
    int i;
    for (i = 0; i < num; i++)
    {
        cout << i << " ";
    }
    return 0;
}

Output:

0 1 2 3 4 5 6 7 8 9

The initialization expression will first set the loop variables. When the loop begins, the statement i=0 is executed once. The condition I num is then tested. If the condition is met, the statements within the loop’s body are performed. After the statements in the body are executed, control of the programme is handed to the variable I being increased by one. The expression i++ alters the variables in the loop. The condition I num is evaluated iteratively. When I ultimately becomes bigger than num, the for loop ends, rendering the condition i<num false

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in