Mark As Completed Discussion

Looping: while Loop

In C++, while loops are used when number of iterations is not known before entering the loop. Sometimes, this makes them a more flexible tool for programmers to use in certain situations. For example, we might utilize a while loop when analyzing real-time data in the AI financial prediction sphere, where we don't necessarily know for how many cycles the data needs to be processed.

The structure of a while loop is as follows:

TEXT/X-C++SRC
1while (condition) {
2    statement(s);
3}
  • Condition is tested; if it's true, the code inside the loop is executed. If it's false, the code inside the loop does not execute and the flow of control moves to the next statement in the program after the loop.
  • After the code inside the loop executes, the flow of control jumps back up to the condition. Hence, the condition is now re-evaluated.
  • If it is still true, the loop executes again and this process repeats.
  • If the condition is false, the loop does not execute and control skips to the next line immediately following the loop.

Continuing the context of our financial AI predictions, let's say we have a variable number of stock portfolios to analyze. Here's how we can use a while loop:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  int portfolio = 1;
6  while (portfolio <= 5) {
7    cout << "Analysis on stock portfolio number " << portfolio << " completed.\n";
8    portfolio++;
9  }
10  return 0;
11}

The while loop checks each portfolio until there are no portfolios left to check, thus being responsive to the real-time nature of financial data.

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