C++ Tutorial for beginners – Loops

Basics of C++ | Variables | If statements | Loops | Functions

 

 

What a loop does is loops through the same piece of code over and over until it has gone through the code a certain number of times.

 

FOR loops

 

1

2

3

4

5

6

7

8

9

10

#include <iostream.h>

 

int main()

{

            for (int i = 0; i <= 5; i++)

            {

                        cout << i << endl;

            }

            return 0;

}

This will print 0 to 5 on the screen. It does this because it keeps going over cout << i << endl; until i = 5

 

 

5

for (int i = 0; i <= 5; i++)

 

First of all, the first time it is run it will set i to 0, then it will go to the next part after the semi-colon (i <=5) and this is saying keep looping through while i is less than or equal to 5 and the next part (i++) will add 1 to i every time it loops through so that i doesn’t stay the same the whole time.

 

 

 

Another example: WHILE loops

 

1

2

3

4

5

6

7

8

9

10

11

12

#include <iostream.h>

 

int main()

{

            int x = 0;

            while (x <= 5)

            {

                        cout << x << endl;

                        x++;

            }

            return 0;

}

This example will do the same thing as for, but can be used for different things

 

 

6

while (x <= 5)

 

This is saying loop the code while x is less than or equal to 5

 

9

x++;

 

This just adds one to x every time it goes through.