3 x 3 matrix

Oct 23, 2013 at 8:55pm
Hi everyone,

below is my code, I am just trying to make a 2d 3 x 3 array. This code works so long as you are happy with the user inputting the 9 numbers necessary but I actually want to specify a particular set of nine numbers within the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<cmath>

int main(){

int matrix[3][3];

for(int i=0; i<3; i++)
{
        for(int j=0; j<3; j++){
                std::cin>>matrix[i][j];
                }
} 

std::cout<<matrix[1][1]<<std::endl;   //this line is so I can check that it has
                                    //worked by making it print one of 
                                    //the elements of the matrix

system("pause");

}


The set of 9 numbers is {5,7,3,1,8,4,2,7,6}. So could you please tell me what the line of code I would need to write in place of the std::cin line in order that the numbers are not input by the user.

Would greatly appreciate any help.
Last edited on Oct 23, 2013 at 8:56pm
Oct 23, 2013 at 8:59pm
One option would be to explicitly assign each number to the appropriate array element.

Or assign them all at once.
Oct 23, 2013 at 9:05pm
I've only ever seen it done using for loops, do you mean do something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<cmath>

int main(){

int matrix[3][3];

matrix[0][0]=5;
matrix[0][1]=7;
matrix[0][2]=3
//etc. etc.

std::cout<<matrix[1][1]<<std::endl;  
system("pause");

}


How would I do that all at once?
Oct 23, 2013 at 9:50pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
int main()
{
    int matrix[3][3] = { {5,7,3},
                         {1,8,4},
                         {2,7,6} };

    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}
Last edited on Oct 23, 2013 at 9:51pm
Oct 23, 2013 at 10:23pm
Thanks for the help, this works nicely.
Topic archived. No new replies allowed.