C++ Code Which Makes the User Input the Rows and Columns in a Multidimensional Array
Im Making a Program Which Displays a Multiplication Table, Which the User Prompts the Number of Rows and Columns, This Program Displays the Table but the...
im making a program which displays a multiplication table, which the user prompts the number of rows and columns, this program displays the table but the number of columns and rows should be the same, if i input a different number,an error happens.
#include <iostream>
using namespace std;
int main()
{
int r,c;
cout<<"How many rows?: ";
cin>>r;
cout<<"How many Columns?: ";
cin>>c;
int table[r][c];
//assigns each element
for (int i = 1; i <= r; i++)
{
for (int j = 1; j <= c; j++)
{
table[i][j] = i * j;
}
}
//prints the table
for (int i = 1; i <= r; i++)
{
for (int j = 1; j <= c; j++)
{
cout << table[i][j] << '\t';
}
}
system("pause");
return 0;
}
2 Answers
Array starts at index 0 and if array size is r arr[r] is illigal to access. So you need to do:
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
table[i][j] = i * j;
}
}
//prints the table
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
cout << table[i][j] << '\t';
}
}
Hi like Jonathan Potter said arrays start at 0 in C/C++. Plus:
int r,c;
cout<<"How many rows?: ";
cin>>r;
cout<<"How many Columns?: ";
cin>>c;
int table[r][c];
Is a really bad practice you should avoid. Effectively, you're creating a table using non-static variables.
This question was already answered here