Alex Chan
Alex Chan

Reputation: 29

Enter values into a 2d array and print

I am trying to write a C++ program that asks for inputs for a 3 by 3 array and then prints them. I am trying to print it but am not sure why it is just giving me 0 for each val

#include <iostream>

using namespace std;

const int row = 3;
const int col = 3;

void printMatrix(int array[row][col]) 
{
    int i, j;
    cout << endl << "Matrix " << endl;

    for(i = 0; i < row; i++) 
    {
        cout << endl;
        for(j = 0; j < col; j++) 
        {
            cout << array[row][col] << "\t";
        }
    }

    cout << "\n";
}

int main()
{
    int i, j, array[row][col];

    for(i = 0; i < 3; i++) 
    {
         for(j = 0; j < 3; j++) 
         {
             cout << "Enter a value for Row " << i + 1 << " Col " << j + 1     << ": "
             cin >> array[i][j];
         }
     }

     printMatrix(array);

}

Console Output:

Enter a value for Row 1 Col 1: 1

Enter a value for Row 1 Col 2: 2

Enter a value for Row 1 Col 3: 3

Enter a value for Row 2 Col 1: 1

Enter a value for Row 2 Col 2: 2

Enter a value for Row 2 Col 3: 3

Enter a value for Row 3 Col 1: 1

Enter a value for Row 3 Col 2: 2

Enter a value for Row 3 Col 3: 3

Output Matrix:

0       0       0

0       0       0

0       0       0

Upvotes: 0

Views: 99

Answers (2)

Rahul Bhayana
Rahul Bhayana

Reputation: 1

You just need to change the printMatrix() function. Change this function as below:

cout << array[i][j] << "\t";

And put semicolon (;) at the end of the cout statement in the main function.

Upvotes: 0

Ratul Sharker
Ratul Sharker

Reputation: 8011

the problem is here

cout << array[row][col] << "\t";

try

cout << array[i][j] << "\t";

Upvotes: 1

Related Questions