I am a new CS student and am having a hard time understanding 2 dimensional arrays. Right now I am just trying to print it out 1 row at a time.
This is my code
#include <stdio.h>
#define N 3
int main(void)
{
int array[N][N], i, j, rows[N], cols[N];
for(i=0;i<N;i++)
{
printf("Enter row %d: ", i+1);
for(j=0;j<N;j++)
scanf("%d", &array[i][j]);
}
printf("The 5 rows you entered are: \n");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
printf("%d", array[i][j]);
printf("\n");
}
}
printf("\n");
return 0;
}
I would like to have the program print out:
1 2 3
1 2 3
1 2 3
If I add the \n
it prints out:
1\n
2\n
3\n
1\n
2\n
3\n
1\n
2\n
3\n
Imagine the \n's as what the screen is printing out, I am trying to represent what the code prints out. I am having trouble getting this box to print out exactly what I am typing in. It won't let me hit enter over and over to represent what is actually on the command screen.
without the /n
it prints out
123123123
I am also trying to add rows and columns. I managed to find some code, and understand most of it, except for one line. This is the code.
#include <stdio.h>
int main(void)
{
int i, j, array[5][5], rows[5],cols[5];
for(i=0;i<5;i++)
{
printf("Enter row %d: ", i+1);
for(j=0;j<5;j++)
scanf("%d", &array[i][j]);
}
**for(i=0;i<5;rows[i]=cols[i]=0,i++);**
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
rows[i]=rows[i]+array[i][j];
cols[j]=cols[j]+array[i][j];
}
}
printf("\nRow Totals: ");
for(i=0;i<5;i++)
printf("%d\t", rows[i]);
printf("\nColumn Totals: ");
for(i=0;i<5;i++)
printf("%d\t", cols[i]);
printf("\n");
return 0;
}
for(i=0;i<5;rows[i]=cols[i]=0,i++);
is the line I do not understand. First off, I don't really understand the rows[i]=cols[i]=0,i++
. And second off, I don't understand why there is a semicolon after it. I thought for statements did not use semicolons, but the program does not work correctly without this line, or without the semicolon. When I try to use it without this line of code, it gives me crazy answers, I am assuming because the elements in the array are not set to 0 and this line of code sets the elements of the arrays to 0. Can someone give me another line of code that might be more understandable for someone relatively new to C? And maybe explain to me why it uses a semicolon?