Reputation: 27
I wrote a simple array which I store 3x3 matrix. But when I run the code it doesn't give 3x3 matrix. just gives a single column as output.
class sucks
{
public static void main(String[] args)
{
int g[][]=new int[3][3];
int h,k,l=0;
for(k=0;k<3;k++)
{
for(h=0;h<3;h++)
{
g[k][h]=l;
l++;
}
}
for(k=0;k<3;k++)
{
for(h=0;h<3;h++)
{
System.out.print(g[k][h]+" ");
System.out.println();
}
}
}
}
The out put is like this
0
1
2
3
4
5
6
7
8
Upvotes: 0
Views: 306
Reputation: 93842
Just print a new line for each row. Like this :
for(k=0;k<3;k++){
for(h=0;h<3;h++){
System.out.print(g[k][h]+" ");
}
System.out.println();
}
To improve your code, you could also change your for loops like this :
for(k=0;k<g.length;k++){
for(h=0;h<g[k].length;h++){
Upvotes: 5