Saturday, April 19, 2025

C++ For Loop

For loops wil help us to execute operations repeatedly. They are best understood with practical examples.

Run this code and then we will explain:

#include <iostream>

using namespace std;

int main() {

    int counter = 1;

    for (counter; counter <= 20; counter = counter + 1) {
        cout << "Counter at the Moment: " << counter << endl;
    }

    return 0;

}

Result:

Counter at the Moment: 1
Counter at the Moment: 2
Counter at the Moment: 3
Counter at the Moment: 4
Counter at the Moment: 5
Counter at the Moment: 6
Counter at the Moment: 7
Counter at the Moment: 8
Counter at the Moment: 9
Counter at the Moment: 10
Counter at the Moment: 11
Counter at the Moment: 12
Counter at the Moment: 13
Counter at the Moment: 14
Counter at the Moment: 15
Counter at the Moment: 16
Counter at the Moment: 17
Counter at the Moment: 18
Counter at the Moment: 19
Counter at the Moment: 20

Process returned 0 (0x0)   execution time : 0.058 s
Press any key to continue.

Outside for loop we will create starting point "counter" and set value 1 for it. 

int counter = 1;

Then, inside for loop we have starting point (counter), ending point (counter <= 20), and how to jump from one value to another, in this case "counter = counter + 1".

For every step, operation of simple printing counter value at the moment of time will be done:

 for (counter; counter <= 20; counter = counter + 1) {
        cout << "Counter at the Moment: " << counter << endl;
    }

So, generic structure of for loop is this one:

int starting_point = some value;

for (starting_point; starting_point <= ending_podint; starting_point = starting_point + 1) {
    cout << "Counter at the Moment: " << starting_point << endl;
}

There's no need to memorize that, we will use it all the time.

For Loop Simplification

Sure, we can have starting point inside for loop. This time we will use some abstract x variable:

#include <iostream>

using namespace std;

int main() {

    for (int x = 0; x <= 20; x += 1) {
        cout << "x at the Moment: " << x << endl;
    }

    return 0;

}

Result:

x at the Moment: 0
x at the Moment: 1
x at the Moment: 2
x at the Moment: 3
x at the Moment: 4
x at the Moment: 5
x at the Moment: 6
x at the Moment: 7
x at the Moment: 8
x at the Moment: 9
x at the Moment: 10
x at the Moment: 11
x at the Moment: 12
x at the Moment: 13
x at the Moment: 14
x at the Moment: 15
x at the Moment: 16
x at the Moment: 17
x at the Moment: 18
x at the Moment: 19
x at the Moment: 20

Process returned 0 (0x0)   execution time : 0.060 s
Press any key to continue.

That also means that "x = x + 1" can be written as "x += 1". It's a little weird but we will use it a lot in programming.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...