Multiplication Table with Loopings in C++

Let's solve the repetition structure list exercise:


  • Make a C++ program that asks the user for an integer and displays their multiplication table.


Multiplication table with FOR in C++

First, we ask the user for a number and store it in the num variable.
Let's also use an aux control variable.

This variable, inside the FOR loop, goes from 1 to 10, to build the multiplication table.
Then just multiply one by aux in each iteration and display the result.

See how our code looked:
#include <iostream>

using namespace std;

int main()
{
    int num, aux;

    cout << "Number: ";
    cin >> num;

    for(aux=1 ; aux<=10 ; aux++)
        cout<<num<<" * "<<aux<<" = " << num*aux <<endl;

    return 0;
}

Multiplication table with WHILE and DO WHILE

You can also do the same with WHILE looping, see:
#include <iostream>

using namespace std;

int main()
{
    int num, aux=1;

    cout << "Number: ";
    cin >> num;

    while(aux<=10){
        cout<<num<<" * "<<aux<<" = " << num*aux <<endl;
        aux++;
    }

    return 0;
}
Note that we must first initialize the aux variable and increment it inside WHILE, just as we do in the FOR structure header.

We can also increment our code and use while, to display as many tables as the user wants, just for when they type 0:




#include <iostream>

using namespace std;

int main()
{
    int num, aux;

    do{
        cout << "Number: ";
        cin >> num;

        for(aux=1; aux<=10 ; aux++)
            cout<<num<<" * "<<aux<<" = " << num*aux <<endl;
        cout<<endl;
    }while(num);

    return 0;
}

No comments:

Post a Comment