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 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;
}
1

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';
        }
    }
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest