Search code examples
c++arraysfor-loopmultidimensional-arraynested-loops

multiplication table on two dimensional array


I did a multiplication table on two dimensional array but I want too change this code and do it on 5 values which I input for ex.

I will input:

   2.5 3.0 4.6 6.3 8.1
2.5
3.0
4.6
6.3
8.1

and it will multiplicate 2.5 * 2.5 etc.

int tab[5][5];
    for(int i=1; i<=5; i++)
    {
        for(int y=1; y<=5; y++)
        {
            tab[i-1][y-1]=i*y;
            cout << tab[i-1][y-1] << " | ";
        }
        cout << endl;
    }

Any tips on how can I do this?


Solution

  • Okay, now the assumption is that this 2D array is always square, and the column values are the same as the row values (like you show in your example).

    You will need to store these values that we want to multiply. Let's call that array of values x.

    You won't have to change much in your current code, but rather than i*y, we want to do x[i] * x[y]. NOTE: you cannot start the loops from 1, start i and y from zero. Also, you will then need to get rid of "-1" when indexing tab[i][y]

    Oh, and I almost forgot. If you wish to use decimals, int cannot be used. Use float instead. You might need to round them to 1 decimal using some tricks that I will show below:

    float tab[5][5];
    float x[5]; // You will have to give x the 5 values that you want to multiply
    for(int i=0; i<=4; i++)
    {
        for(int y=0; y<=4; y++)
        {
            tab[i][y] = x[i] * x[y]; // This can have many decimals!
            tab[i][y] = roundf(tab[i][y] * 10) / 10; // This will multiply with 10 to shift the number 1 decimal place, then we round it to zero decimals, then we divide it with 10, to add 1 decimal. You can change to 100 if you want 2 decimals
            cout << tab[i][y] << " | ";
        }
        cout << endl;
    }
    

    Hope this helps! ^_^