Search code examples
calgorithmloopsmultiplication

Multiplication of numbers from a to b


I need to write algorithm, that multiplies numbers from a to b without input (scanf). Like this:

a = 2;
b = 6;

2 * 3
2 * 4
...
2 * 6

I have my algorithm:

void main()
{
    int dist = 1;
    int a = 2;
    int b = 5;
    for (int i = a; a <= b; a++) {
        printf("%d", a * a++);
    }
}

but it doesn't work correct


Solution

  • This is because you are increasing a (a++) two times in your example above. Also you mixed up a and i a little bit. Correct one is:

    int a = 2;
    int b = 5;
    for (int i = a; i <= b; i++)
    {
        printf("%d * %d = %d\n", a, i, a * i);
    }
    

    which prints:

    2 * 2 = 4

    2 * 3 = 6

    2 * 4 = 8

    2 * 5 = 10