0

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;
}
Kimina1462
  • 3
  • 1
  • 1
  • 3

2 Answers2

1

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';
        }
    }
deeiip
  • 3,319
  • 2
  • 22
  • 33
  • additional question before i close this topic, where would i insert the '\n' text to make it look like a multiplication table. – Kimina1462 Nov 27 '14 at 01:41
0

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

Community
  • 1
  • 1
Florian
  • 855
  • 7
  • 12