Mark As Completed Discussion

Looping Structures

Looping structures are control structures that allow us to execute a block of code repeatedly. They are used when we want to perform a certain task multiple times.

There are three looping structures in C++: while loops, do..while loops, and for loops.

While Loops

A while loop repeatedly executes a block of code as long as a specified condition is true. The basic syntax of a while loop is as follows:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  // Initialize a counter variable
6  int count = 0;
7
8  // Execute the loop while the condition is true
9  while (count < 5) {
10    cout << "Count: " << count << endl;
11    count++;
12  }
13
14  return 0;
15}

In this example, the program uses a while loop to print the value of the count variable as long as it is less than 5.

Do..While Loops

A do..while loop is similar to a while loop, but the condition is checked after the block of code is executed. This means that the block of code is always executed at least once. The basic syntax of a do..while loop is as follows:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  // Initialize a counter variable
6  int count = 0;
7
8  // Execute the loop at least once, then check the condition
9  do {
10    cout << "Count: " << count << endl;
11    count++;
12  } while (count < 5);
13
14  return 0;
15}

In this example, the program uses a do..while loop to print the value of the count variable. The loop continues as long as the condition count < 5 is true.

For Loops

A for loop is used when we know the number of iterations in advance. It combines the initialization, condition check, and iteration in a single line. The basic syntax of a for loop is as follows:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  // Execute the loop for a specific number of iterations
6  for (int i = 0; i < 5; i++) {
7    cout << "Count: " << i << endl;
8  }
9
10  return 0;
11}

In this example, the program uses a for loop to print the value of the i variable from 0 to 4.

Looping structures are powerful tools for automating repetitive tasks and iterating over collections of data. They allow us to write concise and efficient code.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment