2-Dim array

I want to write a program to read in 15 integers from the user, and then store them
in a 5x3 array, and print out the numbers as a 3x5 array.
Good for you
closed account (j3Rz8vqX)
Pseudo code(simply ideas):

Create a 5x3 array of integers.int myArray[3][5];

Use a loop.//Your choice: for,do,while;
This will control your columns.

Prompt the user for a integer number.

Store the value into your array. (myArray[y][x] --- where y is rows, x is columns.)

Increment the x somehow, and repeat 4 more times.

That gives you one row.

To get the other three, embed the loop above in another loop that controls your y variable value. This will control your rows.

I'm sure you can do the printing yourself.
I have written this, but it doesn't work :( I want the array to be displayed in a table with 3 rows and 5 columns.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const int r=5;
const int c=3;
int myarray[r][c];

for (r=0;r<5;r++)
     for (c=0;c<3;c++)
     {
          cin>>myarray[r][c];
     }


for (r=0;r<3;r++)
     for (c=0;c<5;c++)
     {
          cout<<myarray[r][c];
     }
Last edited on
closed account (j3Rz8vqX)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int myarray[3][5];
for (int r=0;r<3;r++)
{
     for (int c=0;c<5;c++)
     {
          cout<<"Type an integer: ";
          cin>>myarray[r][c];
          cout<<endl;
     }
}

for (int r=0;r<3;r++)
{
     for (int c=0;c<5;c++)
     {
          cout<<myarray[r][c];
          cout<<" ";
     }
     cout<<endl;
}


Something to work with.
Last edited on
It wont do any good if you only invert the loops, you also have to invert the indices.
Also, you can't change the values of constants dude, so you need different variables for the counters.

Here is your homework

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

const int R=5;
const int C=3;

int main() {
	int r, c;
	int myarray[R][C];
	
	for (r=0; r<R; r++)
	     for (c=0;c<C;c++)
	          cin >> myarray[r][c];
	
	
	for (c=0;c<C;c++) {
	     for (r=0;r<R;r++)
	          cout << myarray[c][r] << endl;

	    cout << endl; // it's no table if you don't insert new lines
	}

	return 0;
}
Reply to Dput: It's working, but not as I wanted. (change 5x3 to 3x5 array)

Reply to andresgl: I wrote this before, but it doesn't work.
Last edited on
closed account (j3Rz8vqX)
Swap all 5's and 3's around.
Topic archived. No new replies allowed.