Skip to main content

Command Palette

Search for a command to run...

Iterative Statements in cpp

Updated
•2 min read•View as Markdown
Iterative Statements in cpp

Iterative statements, also known as loops, are used in C++ to execute a block of code repeatedly. There are three types of loops in C++: the for loop, the while loop, and the do-while loop.

Here is the syntax for each of these loops:

1) for loop

for (initialization; condition; increment/decrement) {
    // code to be executed repeatedly
}

The for loop executes a block of code repeatedly until the condition is no longer true. The initialization is performed before the loop begins, and the increment/decrement is performed after each iteration of the loop. The condition is checked before each iteration.

Here is an example of a for loop in C++:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 5; i++) {
        cout << i << endl;
    }

    return 0;
}

In this example, the loop will execute five times, with the variable "i" being initialized to 0, incremented by 1 after each iteration, and the loop continuing until "i" is no longer less than 5. The output will be:

0
1
2
3
4

2) while loop

while (condition) {
    // code to be executed repeatedly
}

The while loop executes a block of code repeatedly until the condition is no longer true. The condition is checked at the beginning of each iteration.

Here is an example of a while loop in C++:

#include <iostream>
using namespace std;

int main() {
    int i = 0;

    while (i < 5) {
        cout << i << endl;
        i++;
    }

    return 0;
}

In this example, the loop will execute five times, with the variable "i" being incremented by 1 after each iteration, and the loop continuing until "i" is no longer less than 5. The output will be:

0
1
2
3
4

3)do-while loop

do {
    // code to be executed repeatedly
} while (condition);

The do-while loop executes a block of code repeatedly until the condition is no longer true. The code is executed at least once, regardless of the condition, and the condition is checked at the end of each iteration.

Here is an example of a do-while loop in C++:

#include <iostream>
using namespace std;

int main() {
    int i = 0;

    do {
        cout << i << endl;
        i++;
    } while (i < 5);

    return 0;
}

In this example, the loop will execute five times, with the variable "i" being incremented by 1 after each iteration, and the loop continuing until "i" is no longer less than 5. The output will be:

0
1
2
3
4
S

Your work is really meant to us...

More from this blog

C++ Concepts:Everything You Need to Know

26 posts