Search code examples
c++functionloopsfor-loopmultiplication

Multiplication with functions in C++


I am new to functions and i am really trying to understand how they work, my teacher gave us a problem where by we were to pass a number to a function between the range of 1-12 and the function was then meant to do the times tales of that number so I asked the user to enter a number and if the number is less then 1 and greater then 12 exit, else pass the number to the function and then I used a for loop to do the multiplication for me (as far as I am aware) but nothing seems to happen? Νo doubt I am doing something really stupid, any help is much appreciated.

#include <iostream>
using namespace std;

int TimesTables (int num);

int main(int argc, const char * argv[]) {
    int number;
    cout << "enter a number to multiply by, with a range of 1-12: ";
    cin >> number;
    if (number < 1 && number > 12)
        return EXIT_FAILURE;
    else {
        int tables = TimesTables(number);
        cout << tables;
    }
    return 0;
}
int TimesTables (int num) {

    for ( int i = 0; num <=12; i ++)
        num = num * i;
    return num;
}

Solution

  • for ( int i = 0; num <=12; i ++)
        num = num * i;
    

    Here i starts from 0, so any multiplication you do afterwards doesn't affect the result (num). Moreover, you want to go from 1 to 12, so you should start from 0 and finish at 12 - 1, or start from 1 and finish at 12.

    So change this:

    for ( int i = 0; num <=12; i ++)
    

    to this:

    for ( int i = 1; i <=12; i ++)
    

    since you want to stop when i reaches 12, not num, i is the counter of the !