Loops in C++ - ProgrammerTech
Language:

Search

Loops in C++

  • Share this:
Loops in C++

 Loops in C++

Loops are used to repeat a code multiple times. Any code we want to be executed multiple times we write it inside the Loop loop, and this loop re-executes the code under certain conditions that the programmer defines.

Types of loops in C++

  1. For Loop.
  2. While Loop.
  3. Do While Loop.

 

For Loop in C++

A For Loop is a condition that is used to repeat something many times and usually contains a final value.

How to use the For Loop

for ( initial value ; coalition ; increment )
{
	Statements;
}

whereas:

  • initial value The start of the session.
  • coalition is the ending condition on which the session ends.
  • increment is the difference of the variable per cycle eg an increment of 1 per cycle.

 

example 1

#include <iostream>
using namespace std;
int main()
{
    int i;
    for(i=1; i<10; i++)
    cout << "Programmer Tech" << endl;
}

When you run this code, the result will be:

Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech

We note that he printed the word for us 9 times because we started with the number 1.

Example 2

#include <iostream>
using namespace std;
int main()
{
    int a = 0;
    for(;a < 10;)
    {
        cout << a << endl;
        a++;
    }
}

The result of this code will be

0
1
2
3
4
5
6
7
8
9

We can shorten the previous code to one line as follows:

#include <iostream>
using namespace std;
int main()
{
    for (int a = 0; a < 10; a++)
    {
        cout << a << endl;
    }
}

 

While Loop in C++

While Loop consists of only one condition, if this condition is true, it stays inside the loop, and if it is false, the loop will stop and the variable will be outside the parentheses.

How to use the While Loop

while( condition )
{
    / statements
    increment ;
}

example 3

#include <iostream>
using namespace std;
int main(){
	int x = 0;
	while ( x < 10 ) 
	{
		cout << "Programmer Tech" << endl;
		x++;
	}
}

We create a variable x outside the parentheses and assign it a value of 0 and put a loop and condition if x is less than 10 means. As long as it is less than 10, type the word programmer Tech on the screen ten times. And we wrote ++x and the comment x=x+1, in each cycle it will check and add 1 until it is printed ten times. When you run the code, the result will be as follows:

Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech
Programmer Tech

 

Do While Loop in C++

A Do While Loop We use it if we want to run the code multiple times, but we don't know how many times in the selection because we want to stop the execution if a certain condition is met. This loop stops repeating itself if the condition we set for it is met.

How to use the Do While Loop

do
{
statement
}while (condition);

do while is used to iterate a part of a program that has been used multiple times. If the iteration number is not fixed then we must use the loop at least once. The best thing here is to use this do while loop, and the iteration is executed at least once because the state is checked during the loop.

Example 4

#include <iostream>
using namespace std;
int main(){
int x = 0;
do{
    cout << "Saja" << endl;
    x++;
}while(x<5);
return 0;
}

In the example, we set a value of 0, that is, the counting starts from zero, and we wrote the do, then we set the print command for the word Saja. And we give x++ in order to increment by one in each cycle and we set the condition while if x is less than 5, it will complete the cycle for the next cycle, and so it will print the sentence for us five times. When you run this program we will get the result.

Saja
Saja
Saja
Saja
Saja

Example 5

#include <iostream>
using namespace std;
int main(){
	int x = 1;
		do{
			cout << x << endl;
			x++;
		}while(x<=7);
return 0;
}

We created a scalar variable which is x and its value is 1, then we opened the do loop and wrote in it, print the value of x and increment it by 1 each cycle. Then we put a condition after the word while, which is if x is less than or equal to 7 Execute the codes when running the result will be

1
2
3
4
5
6
7

Example 6

#include <iostream>
using namespace std;
int main(){
    int x = 1;
        do{
            int j = 1;
            do{
                cout<<x<<"\n";
                j++;

            }while (j <= 3);
            x++;
        }while(x <= 3);
}

When you run the code, the result will be

1
1
1
1
2
2
2
3
3
3

 

Difference Between While and Do While

 

  • The while initially tests the condition and then executes it if this is true, and nothing may be executed.
  • The do while is executed first and then tests the condition continuously and may have at least one execution.

 

Control sentences with loops

Control statements are used to control the flow of loops, as well as with the switch clause. There are two types of control statements in loops:

  1. Break Statement.
  2. Continue Statement.

 

break clause in C++

The break clause is to stop the loop when a certain condition or several conditions are met, and when it is executed, the loop is stopped (ie exiting the loop). Once the break statement is executed, it stops and exits the entire scope, clears it from memory and then moves to the next code in the program.

How to define the break . clause

This sentence consists of one command and is written on a single line.

break;

Example 7

#include <iostream>
using namespace std;
int main(){
    int count;
    for (count=1;count<=10;count++)
    {
        if (count==5)
            break;
        cout<<count<<"";
    }
    cout<<"\n break out of the loop"<<count<<endl;
    return 0;
}

We created a scalar variable, which is count, and we created an iterative for loop, and we gave the value of the variable count, which is 1 i.e. from the number 1 starts the counter. And we said if the value of the counter is less than or equal to 10 then supply one per cycle by count++. And we set a condition that if the counter value is 5, stop the iterative loop immediately, that is, when it reaches the number 5, the loop is stopped and the numbers for count are printed. After that, we asked to print a sentence and write that the lobby was stopped at the number at which the counter stops. When you run the program, the result will be.

1234
break out of the loop5

We also noticed that the break statement is executed if the condition is true, that is, if the count is 5, nothing will be printed after that, and it will stop and exit the loop.

Example 8

#include <iostream>
using namespace std;
int main(){
    for (int o=0; o<10 ; o++){
        if (o==5) {
            break;
        }
        cout << o << endl;
    }
    return 0;
}

In this example, we told him to print from 1 to 10 and as long as o is less than 10, keep adding 1 in each process and when he reached 5 stops because we set him a break to stop and he showed us the count from 0 to 4. When we run it, we will get the output.

0
1
2
3
4

 

The continue statement in C++

The continue clause moves from the current loop we are working in to the next loop without completing the code included in the current loop. We use the continue clause to override the execution of certain code in the loop, so we use it to override part of the scope code. We use it specifically to stop the current cycle and move to the next cycle in the loop.

How to define the continue . sentence

This sentence consists of one command and is written on a single line.

continue;

Example 9

#include <iostream>
using namespace std;
int main(){
    int count;
    for (count=1;count<=10;count++)
    {
        if (count==5)
            continue;
        cout<<count<<"";
    }
    cout<<"\n break out of the loop"<<count<<endl;
    return 0;
}

We created a scalar variable, which is count, and we created an iterative for loop, and we gave the value of the variable count, which is 1 i.e. from the number 1 starts the counter. And we said if the value of the counter is less than or equal to 10 then supply one per cycle by count++. And we set a condition that if the counter value reached 5, ignore the number 5 and continue to the end, that is, when it reaches the number 5, it is ignored and the loop is completed and the numbers are printed for count. After that, we asked to print a sentence and write that the lobby was stopped at the number at which the counter stops. When you run the program, the result will be.

1234678910
break out of the loop11

This is the same as the first example in break. When we set continue, we ignore the number 5 and continue the cycle until it is finished.

Example 10

#include <iostream>
using namespace std;
int main(){
    for (int o=0; o<10 ; o++){
        if (o==5) {
            continue;
        }
        cout << o << endl;
    }
    return 0;
}

In this example, we told him to print from 1 to 10, and as long as o is less than 10, keep adding 1 in each operation, and when he reached 5, he ignored it because we set him to continue, and he showed us the counter from 0 to 9 and ignored the number 5. When the code is run, it will be The result.

0
1
2
3
4
6
7
8
9

 

Nested spin loop in C++

Nested Loops In this lesson we will learn how to use a for loop inside a second for loop. What would you expect if we repeated a line of code three times?

For example, if we had a for loop, we would have to print the asterisk * three times, and it was this loop. Inside the for loop it iterates three times and prints a new line after the inner for loop has finished.

for (int i = 0; i < 3; i++ )
{
	for (int j = 0; j < 3; j++)
	{
		cout << "* ";
	}
	count << endl;
}

The value of i first starts with 0 and will be passed to the internal for loop and the value of the variable j will start with zero as well. The inner for loop will start printing what's inside and iterating until the inner loop is finished and a new line is printed. You increment the value of i for the outer loop and start spinning again, and you'll go into the inner loop again and define j from zero again. And you do the same work until we produce a square with a width of three stars and a length of three stars, and this is the answer to what happens if we have a line of code that repeats a line of code three times.

Example 11

Write a program in C++ that prints a square of stars.

#include <iostream>
using namespace std;
int main()
{
    int h;
    cout << "Enter the length of the square:" << endl;
    cin >> h;
    for(int j=0; j<h; j++)
    {
        for(int i=0; i<h; i++)
        {
            cout << "* ";
        }
        cout << endl;
    }
    return 0;
}

In the beginning, we created an integer variable named h and put a message that appears to the user at the beginning of the program asking him to enter the length of the desired square. The cin function will receive the values ​​entered by the user. And we entered an external for loop, and this loop will spin the number of h that the user will enter. And the inner loop is the one that will print a line of stars in each cycle and in the end we put cout<<endl in order to put the stars in the second cycle with a new line. And when you run the program and write the number 3, we will get the result.

1-5.webp

And if we enter number 5.

2-4.webp

 

We also notice that when we entered the number 3, a triangular square was printed for us, and when we entered the number 5, a pentagonal square was printed for us.

Example 12

Write a program that prints a rectangle of stars (asking the user to enter the length and width of the square or vice versa).

#include <iostream>
using namespace std;
int main()
{
    int h, w;
    cout << "Enter the width of the box:" << endl;
    cin >> w;
    cout << "Enter the length of the square:" << endl;
    cin >> h;
    for(int j=0; j<h; j++)
    {
        for(int i=0; i<w; i++)
        {
            cout << "* ";
        }
        cout << endl;
    }
    return 0;
}

In this example, we must have two variables for length and width, h and w, and we make a prompt. The user has to enter the length of the square and the width of the square via the cin receive function. And we entered into an iterative loop and it had a variable named j and its value is 0. Then we told him that j is less than h and increment one in each cycle. And we also created an inner loop of type for and inside it was a scalar variable whose value is 0 and is i, then we told it that i is less than. w and increment by one for each turn, and we set it to print an asterisk and for every line ending it starts with another new line. If you enter width 10 and length 6, the result will be.

3-1.webp

 

And if we enter width 9 and length 4 it will be .

4-3.webp

 

example 13

Write a program that asks the user for a number, then the program builds a right-angled triangle from the entered number, where each number repeats over its number, ending with the number one 1.

#include <iostream>
using namespace std;
int main()
{
    int n;
    cout << "Enter a number : ";
    cin >> n;
    for(int i = n; i > 0; i--)
    {
        for (int j = 0; j < i; j++)
            cout << i << " ";
        cout << endl;
    }
    return 0;
}

In the beginning we defined a scalar variable n and then we asked the user to enter a number and we used the cin function to ask the user to type a number to receive it. And we opened an external for loop and this loop had a scalar variable i and its value is the value of the n variable that the user will enter. And we told the program when i is greater than 0 and decrement a number from the outer ring with each cycle ie. If you start from the number 5 in the second cycle, it will become 4 and so on until you reach the number 1. Then we entered the inner for loop and it had a scalar variable j and its value is 0 and we told it j is less than 1 and in each cycle we increment the counter by one. And in the end, through the print function, we told him to print the value of the variable i because it is this variable that will be printed. In each cycle, a second line is descended for the elements of the next loop to be on a new line. If the user enters the number 4, the following will be produced.

5-3.webp

 

If you enter user number 9.

6-3.webp

 

This is the concept of recurring loops and control sentences in a nutshell. If you like the lesson, please support us by sharing it on the means of communication.


Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com