I want to display all entries of 2D array in c++

2669 views c++
-1

I want to create a program that take size of rows and columns of 2D array from user, and then take all entries of array from user. And Finally display all the entries from array[0][0] to array[size][size].

My code is:

#include <iostream>
using namespace std;

int main()
{
    int rows, coloumns;
    int tom[rows][coloumns];
    cout << "Size of array rows: ";
    cin >> rows;
    cout << "Size of array coloumns: ";
    cin >> coloumns;
    for(int count1 = 0; count1 < rows; count1++)
    {
        for(int count2 = 0; count2 < coloumns; count2++)
        {
            cout << "Enter entry of row " << count1 << " and coloumn " << count2 << ": ";
            cin >> tom[count1][count2];
        }
    }
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < coloumns; j++)
        {
            cout << tom[i][j] << endl;
        }
    }
    return 0;
}

Output is:

Size of array rows: 2
Size of array coloumns: 3
Enter entry of row 0 and coloumn 0: 1
Enter entry of row 0 and coloumn 1: 2
Enter entry of row 0 and coloumn 2: 3
Enter entry of row 1 and coloumn 0: 12
Enter entry of row 1 and coloumn 1: 13
Enter entry of row 1 and coloumn 2: 14
12
13
14
12
13
14

It should give output:

1
2
3
12
13
14

What is the problem? Please help.

answered question

You were lucky (or unlucky). You should've gotten a seg-fault.

By the time your array is defined (int tom[rows][coloumns];), the values of rows and coloumns aren't.

1 Answer

2

use std::vector:

#include <iostream>
#include <vector>

int main()
{
    int rows, coloumns;
    std::cout << "Size of array rows: ";
    std::cin >> rows;
    std::cout << "Size of array coloumns: ";
    std::cin >> coloumns;
    std::vector<std::vector<int>> tom(rows, std::vector<int>(coloumns));

    for (int count1 = 0; count1 < rows; count1++)
    {
        for (int count2 = 0; count2 < coloumns; count2++)
        {
            std::cout << "Enter entry of row " << count1 << " and coloumn " << count2 << ": ";
            std::cin >> tom[count1][count2];
        }
    }
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < coloumns; j++)
        {
            std::cout << tom[i][j] << std::endl;
        }
    }
    return 0;
}

output:

Size of array rows: 2
Size of array coloumns: 3
Enter entry of row 0 and coloumn 0: 1
Enter entry of row 0 and coloumn 1: 2
Enter entry of row 0 and coloumn 2: 3
Enter entry of row 1 and coloumn 0: 12
Enter entry of row 1 and coloumn 1: 13
Enter entry of row 1 and coloumn 2: 14
1
2
3
12
13
14

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories