2D arrays

so I'm supposed to output a table showing a multiplication table for 1-5 using a 2D array:

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've got what I think should work below, but the program gives me a lot of random numbers instead of the table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  // this program will output a multiplication table for 1-5

#include <iostream>
using namespace std;

int main()
{
	int table [4] [4];
	int ans;
	// creates the first colomn
	for (int a; a<=4; a++)
	{
		table [a] [0] = a + 1;
	}
	// creates first row
	for (int b; b<=4; b++)
	{
		table [0] [b] = b + 1;
	}	
	
	// fills in the rest of the table
	for (int c=1; c<=4; c++)
	{
		for (int d=1; d<=4; d++)
		{
			table [c][d] = (table [c][0]) * (table [0][d]);			
		}
	}
	
	// prints array
	for (int i = 0; i <= 4; ++i)
    {
        for (int j = 0; j <=4; ++j)
        {
            cout << table[i][j] << "\n";
        }
        cout << endl;
    }

}
Last edited on
Before reading answers to your problem, try reading this tutorial and then seeing if you can fix your own problems.

Arrays
http://www.cplusplus.com/doc/tutorial/arrays/

I can see one really glaring errors you should be able to identify yourself if you compare what you've coded against your problem statement.

Another should be pretty obvious once you've read the tutorial.

But I will tell you that C++ local variables have an undefined value if not initialized.

From Variables / Initialization of variables
http://www.cplusplus.com/doc/tutorial/variables/

When the variables in the example above are declared, they have an undetermined value until they are assigned a value for the first time. But it is possible for a variable to have a specific value from the moment it is declared. This is called the initialization of the variable.

Andy
Last edited on
Try this...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

int main()
{
	int table[5][5];

    int i, j;

    // load the table
    for(i = 1; i <= 5; i++)
    {
        for(j = 1; j <=5; j++)
        {
            table[i-1][j-1] = i * j;
        }
    }

    // print the table
    for(i = 0; i < 5; i++)
    {
        for(j = 0; j <5; j++)
        {
            cout << table[i][j] << " ";
        }
        cout << '\n';
    }

    return 0;
}

Topic archived. No new replies allowed.