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?

No comments:

Post a Comment