Battleroid
Battleroid

Reputation: 881

Cannot enter values for two dimensional array in C++

I'm doing an assignment for a class and it's fairly routine. I've done this before in Java so it's not entirely new to me, however, I'm not entirely sure what's wrong here.

Basically I need to enter information for several row/columns and then print the sum of the column, all of that isn't particularly difficult. However, every time I print my array's contents everything is 1, no matter what.

I'm not sure what's wrong, if someone can tell me why I'd appreciate it.

Oh, forgot to mention, I am using g++ for compiling.

#include <iostream>
#include <cstdio>
using namespace std;

const int ROWS = 4;
const int COLUMNS = 3;

void setupMatrix() {
    // Setup matrix
    double array[ROWS][COLUMNS];

    // Needed? Wouldn't think so.
    // for (int i = 0; i < COLUMNS; i++) {
    //      for (int j = 0; j < ROWS; j++) {
    //              array[i][j] = 0.0;
    //      }
    // }

    // Get array information from user
    for (int i = 0; i < COLUMNS; i++) {
            printf("Row %d\n", (i + 1));
            for (int j = 0; j < ROWS; j++) {
                    printf("Column %d ", (j + 1));
                    cin >> array[i][j];
            }
    }

    // Print array so I can see what's up first
    for (int i = 0; i < COLUMNS; i++) {
            // Row & column separation
            printf("\n");
            for (int j = 0; j < ROWS; j++) {
                    printf("%d ", array[j][i]);
            }
    }

}

int main () {
    setupMatrix();

    return 0;
}

Upvotes: 0

Views: 98

Answers (2)

qPCR4vir
qPCR4vir

Reputation: 3571

You are using:

array[i][j]);

for "cin"and

array[j][i]);

for print: use cout<<array[j][i]);

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

First dimension of the array is ROWS and second is COLUMNS, you got the cycles order wrong. Also to print double use format specifier %lf in the printf. I don't see why you decided to use printf when you read using cin, better use cout for consistency and as this is the typical way to print in C++

Upvotes: 5

Related Questions