Showing posts with label Repetition Statement. Show all posts
Showing posts with label Repetition Statement. Show all posts

BREAK and CONTINUE statements in C++

In this tutorial, we will learn two very important statements, or commands: break and continue in C++.

Statement BREAK in C++

If you did well and in order, the Progressive C++ course, you should already know this break command, because we used in the tutorial:
Switch, case and break

There, when this command was executed, it simply terminated the SWITCH conditional test.
Here he does the same thing, but in this case he serves to break a loop at any moment.

In the code below, C ++ keeps asking the user for a number and calculating its square.

If at any time the user enters 0, the IF becomes true and the break command is triggered, briefly breaking the WHILE loop:
#include <iostream>
using namespace std;

int main()
{
    int num;

    while(true){
        cout<<"Number: ";
        cin >>num;

        if(num==0)
            break;

        cout<<num*num<<endl;
    }

    return 0;
}
That is, when we want to break a loop at some point, we use the BREAK statement, which usually comes within a conditional test, within some looping.

If we have one loop inside another, and inside that is a BREAK statement, only that innermost loop will be broken, okay?

The following code keeps asking the user for grades to average.

If you enter a note that is not valid (below 0 or above 10), the WHILE loop ends and we provide the average of the numbers entered for that invalid note:

#include <iostream>
using namespace std;

int main()
{
    int aux=0;
    float num, sum=0;

    while(true){
        cout<<"Grade: ";
        cin >> num;

        if(num<0 || num>10)
            break;

        sum+=num;
        aux++;
    }

    cout<<"Average: "<<(sum/aux)<<endl;
    return 0;
}
Note that we guarantee that the numbers provided are correct (between 0 and 10), otherwise the loop will end.

The CONTINUE statement in C++

If BREAK terminates the conditional test or repetition statement, the CONTINUE command terminates the iteration only.

That is, skips to the next iteration.

Let's sum all numbers from 1 to 100 except multiples of 4:
#include <iostream>
using namespace std;

int main()
{
    int num, sum=0;

    for(num=1; num<=10 ; num++){
        if(num%4==0)
            continue;
        sum += num;
    }

    cout<<"Total: "<<sum<<endl;
    return 0;
}
Inside the loop we check if the number is divisible by 4, if so, this iteration is skipped, not running the code following CONTINUE, goes to the next iteration normally.

Like BREAK, the CONTINUE command usually occurs under a certain conditional test when you want to exclude a specific looping iteration.

Let's redo the code that averages.

Now, instead of stopping execution, it skips the iteration, not adding that invalid note to the sum:
#include <iostream>
using namespace std;

int main()
{
    int aux=0;
    float num, sum=0;

    while(true){
        cout<<"Grade: ";
        cin >> num;

        if(num>10){
            cout<<"Grade above 10 is invalid"<<endl;
            continue;
        }
        if(num<0){
            cout<<"Negative grade, shutting down and displaying average: ";
            break;
        }

        sum+=num;
        aux++;
    }

    cout<<(sum/aux)<<endl;
    return 0;
}
Note that the average is calculated for valid numbers only. To end looping, you must enter a negative value.

Summation and Factorial with C++ Loops

In this tutorial, we will solve two questions from our list of loop exercises, we will learn how to calculate the sum and factorial of a number, using only FOR or WHILE loops, in C++.

Summation with C++ loopings

The summation of a number n is nothing more than the sum of the numbers from 1 to n.

So first we ask the user for a positive integer and store it in variable n.
We will also use an aux auxiliary variable, which will traverse the values from 1 to n within the loop.

We will also use the sum variable, which will store the sum of all these numbers. Obviously, we must initialize it with value 0.

See how our code is using FOR loop:
#include <iostream>

using namespace std;

int main()
{
    int n, aux, sum=0;

    cout << "Summation: ";
    cin >> n;

    for(aux=1 ; aux<=n ; aux++)
        sum += aux;

    cout << "Summation: " << sum << endl;

    return 0;
}
Now with WHILE:
#include <iostream>

using namespace std;

int main()
{
    int n, aux=1, sum=0;

    cout << "Summation: ";
    cin >> n;

    while(aux<=n){
        sum += aux;
        aux++;
    }

    cout << "Summation: " << sum << endl;

    return 0;
}
With WHILE looping, can be calculated several times and typing 0 to end the loop:
#include <iostream>
using namespace std;

int main()
{
    int n, aux, sum;

    do{
        cout << "Summation: ";
        cin >> n;
        sum = 0;

        for(aux=1 ; aux<=n ; aux++)
            sum += aux;

        cout << "Summation: " << sum << endl;
        cout<<endl;
    }while(n);

    return 0;
}

Factorial using loops in C++

If the sum totals all numbers from 1 to n, the factorial multiplies all numbers from 1 to n.

The factorial symbol of a number is !.

For example:
4! = 1 x 2 x 3 x 4 = 24
5! = 1 x 2 x 3 x 4 x 5 = 120

Instead of sum let's use prod to store the product, and inicialize with 1.
And instead of adding (+=), let's multiply (*=).

Using FOR loop:
#include <iostream>

using namespace std;

int main()
{
    int n, aux, prod=1;

    cout << "Factorial: ";
    cin >> n;

    for(aux=1 ; aux<=n ; aux++)
        prod *= aux;

    cout << "Factorial: " << prod << endl;

    return 0;
}
WHILE:
#include <iostream>
using namespace std;

int main()
{
    int n, aux=1, prod=1;

    cout << "Factorial: ";
    cin >> n;

    while(aux<=n){
        prod *= aux;
        aux++;
    }

    cout << "Factorial: " << prod << endl;

    return 0;
}
DO WHILE:
#include <iostream>
using namespace std;

int main()
{
    int n, aux, prod;

    do{
        cout << "Factorial from: ";
        cin >> n;
        prod = 1;

        for(aux=1 ; aux<=n ; aux++)
            prod *= aux;

        cout << "Factorial: " << prod << endl;
        cout<<endl;
    }while(n);

    return 0;
}
Simple, right?

FOR Repetition Statement - C++ controlled loop

Concluding the presentation of the repetition structures of our C ++ Course, we will present the FOR statement, the controlled loop.

FOR repetition statement in C++

The FOR repetition statement has the following syntax:
for(inicialization ; conditional_test ; update){
   // codes that run if
   // the conditional test
   // is true
}
Come on.
The FOR repetition statement has three expressions within it, separated by semicolons.

The loop begins with some kind of initialization, usually a count variable, with some initial value.

After this initialization, conditional testing occurs. If true, the code inside the FOR loop braces is executed.
After each iteration, the 'update' occurs, where we usually update the counter value, most commonly it is a variable that will increment or decrement.

Then again the conditional test is performed, if true, again the FOR code is executed. After this iteration, the update occurs again.

FOR loop usage example

In programming, an example is worth a thousand words.
Let's count from 1 to 10, using the for loop, the code is as follows:
#include <iostream>
using namespace std;

int main()
{
    int count;

    for(count=1; count<=10 ; count++){
        cout << count << endl;
    }

    return 0;
}
Our control variable is count, which starts at 1.
Let's print it on screen as long as its value is less than or equal to 10.

At each iteration, we increment it by one (count++) because we want it to go from 1 to 10.

Note that we already did that in the WHILE loop, but we initialized the variables before the loop, inside that we updated the variable with each loop and the conditional test occurred inside the WHILE parentheses.

It occurs the same way in the FOR loop, but in a more organized way.

Using the FOR Repetition Statement

Let's do the opposite now, a countdown, which counts from 100 to 1.
For this, we initialize our control variable to 100.

The test to be performed is: count> 0
That is, as long as the variable has a value above 0, iterations of the FOR loop will occur.

And with each iteration we have to decrease the count, because it goes from 100 to 1, one by one.
See how our code looked:

#include <iostream>
using namespace std;

int main()
{
    int count;

    for(count=100; count>0 ; count--){
        cout << count << endl;
    }

    return 0;
}
Not always, however, we will increment or decrement by 1 in 1.
We can update our variables as we wish.

For example, let's print all even numbers from 1 to 1000 on the screen.
The first even is 2, so we initialize our variable with this value.

Let's increment by 2: count += 2

And the test is as long as the variable is less than or equal to one thousand: count <= 1000
#include <iostream>
using namespace std;

int main()
{
    int count;

    for(count=2; count<=1000 ; count+=2){
        cout << count << endl;
    }

    return 0;
} 
See the incredible speed with which this code executes.
Do you doubt the ability of C ++? Put 1 million.

When to use the FOR loop

Often we want to loop with a certain number of iterations.
For example, when asking for a student's grades, let's ask for as many grades as there are to average.

To calculate your income tax, we need to add up your entire salary of the year, ie 12 salaries.

The FOR loop is ideal when you know exactly the number of iterations you are going to do: "oh, I want to calculate this in this range from x to y", so bang, use the FOR repetition statement.

When you don't know when looping should end or have less control over how many iterations to occur, then use the WHILE loop.

Remembering that, deep down, they are absolutely the same thing.

It will only be easier to work with FOR sometimes and WHILE at other times.

FOR Repetition Statement

Create a program that asks how many grades you want to average, then asks each of those grades and finally displays the average.

Let's store the number of notes we will ask for in variable n.
The next step is to ask for grade by grade, and here comes the ace in the hole: calculate the sum of all grades.

Within the FOR, the control variable aux goes from grade 1 to the grade n, asking one by one and storing the grade in the variable grade.

Let's store in the sum variable, the sum of all these grades.
Finally, we display sum/n to display the average.

See our C ++ code:
#include <iostream>
using namespace std;

int main()
{
    int aux, n;
    float grade, sum=0;

    cout <<"How many topics: ";
    cin >> n;

    for(aux=1; aux<=n ; aux++){
        cout <<"Grade "<<aux<<": ";
        cin >> grade;
        sum += grade;
    }

    cout << "Average: "<<(sum/n)<<endl;

    return 0;
}
Notice how this repetition statement is controlled: it will always run 'n' iterations, whatever the value of 'n' (obviously, the number of grade must be a positive integer value).

You can fill in 2 grades, 3 grades, a thousand grades, a million grades ...
Powerful, isn't this FOR command?