Ryan Arellano Ryan Arellano - 1 month ago 21
Java Question

Array multiplication table

I want understand more about arrays. I came up with this question of creating multiplication table that would display this way

1 2 3 4 5

2 4 6 8 10

3 6 9 12 15

4 8 12 16 20

5 10 15 20 25


I though of using arrays this way

int myArray[] = {1,2,3,4,5};
int myArray2[] = {1,2,3,4,5}


The first array would serve as the horizontal set and the 2nd would be the vertical.
The problem is I dont know how exactly am I going to multiply each index and display them as a multiplication table.

Answer

You can use something like this assuming you are using Java:

for (int j = 1; j <= 5; j++)
{
    for (int i = 0; i < myArray.length; i++)
         {
             System.out.print(array[i] * j + " ");
             if (i == myArray.length - 1) 
                {
                    System.out.println();
                }
         }
    j++;
}

The outer loop will walk the numbers from 1 to 5.

The inner loop will use the outer loop's 'j' value to multiply each number in your array.

Then it puts an empty line whenever the inner loop reaches the end of the array.