Monday, June 19, 2023

Looping Statements in C++

 

Looping Statements in C++

 

In C++, there are several looping statements that you can use to repeat a block of code multiple times. The most commonly used looping statements are:

 

1. **for loop**: The `for` loop allows you to specify an initialization expression, a condition, and an increment or decrement expression, all in a single line. The syntax for a `for` loop is as follows:

 

```cpp

for (initialization; condition; increment/decrement) {

    // code to be executed

}

```

 

Here's an example that prints the numbers from 1 to 5 using a `for` loop:

 

```cpp

for (int i = 1; i <= 5; i++) {

    cout << i << " ";

}

```

 

2. **while loop**: The `while` loop repeatedly executes a block of code as long as the specified condition is true. The syntax for a `while` loop is as follows:

 

```cpp

while (condition) {

    // code to be executed

}

```

 

Here's an example that prints the numbers from 1 to 5 using a `while` loop:

 

```cpp

int i = 1;

while (i <= 5) {

    cout << i << " ";

    i++;

}

```

 

3. **do-while loop**: The `do-while` loop is similar to the `while` loop, but the condition is checked at the end of the loop. This guarantees that the loop body is executed at least once. The syntax for a `do-while` loop is as follows:

 

```cpp

do {

    // code to be executed

} while (condition);

```

 

Here's an example that prints the numbers from 1 to 5 using a `do-while` loop:

 

```cpp

int i = 1;

do {

    cout << i << " ";

    i++;

} while (i <= 5);

```

 

These are the three main looping statements in C++. Each of them has its own use cases depending on the requirements of your program.

No comments:

Post a Comment