Mark As Completed Discussion

Looping: for Loop

In C++, for loops are traditionally used when the number of iterations is known before entering the loop. Structure of a for loop is as follows:

TEXT/X-C++SRC
1for (initialization; condition; increment/decrement) {
2    statement(s);
3}
  • Initialization sets a counter to an initial value.
  • 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 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 increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
  • The condition is now re-evaluated. If it is true, the loop executes and the process repeats itself (flow of control jumps back up to increment/decrement, and so on).
  • If the condition is false, the loop does not execute and control skips to the next line immediately following the loop.

In the context of our financial AI predictions, let's say we have five stock portfolios to analyze. Here's how we can use a for loop:

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

Every time the loop iterates, the value of portfolio increases by 1 until it eventually becomes 6, at which point the loop ends because our condition portfolio <=5 is no longer met.

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