Hi,
I am trying to get an example program to run, but it isn't working. I've probably typed something incorrectly, but I have checked three times and I just don't see it. Anyway, it's a sample program from the C Primer Plus book that is supposed to add the rows and columns from an array. The book says that the output should be:
row 0 = 20
row 1 = 24
row 2 = 36
col 1 = 19
col 2 = 21
col 3 = 23
Now, when I run the program, the rows add up just fine. The cols, however, all display the letter d. Could you please have a look at the code and tell me what I missed? Also, could you please tell me how to start the row with 1 instead of 0 as it does in the book? Thanks!
Ren
#include <stdio.h>
#define ROWS 3
#define COLS 4
void sum_rows(int ar[][COLS], int rows);
void sum_cols(int [][COLS], int rows);
int sum2d(int (*ar) [COLS], int rows);
int main(void)
{
int junk[ROWS][COLS] = {
{2,4,6,8},
{3,5,7,9},
{12,10,8,6}
};
sum_rows(junk, ROWS);
sum_cols(junk, ROWS);
printf("Sum of all elements = %d\n", sum2d(junk, ROWS));
return 0;
}
void sum_rows(int ar[][COLS], int rows)
{
int r;
int c;
int tot;
for (r = 0; r < rows; r++)
{
tot = 0;
for (c = 0; c <COLS; c++)
tot += ar[r][c];
printf("row %d sum = %d\n", r, tot);
}
}
void sum_cols(int ar[][COLS], int rows)
{
int r;
int c;
int tot;
for(c = 0; c < COLS; c++)
{
tot = 0;
for (r = 0; r < rows; r++)
tot += ar [r][c];
printf("col %d sum = d%\n", c, tot);
}
}
int sum2d(int ar[][COLS], int rows)
{
int r;
int c;
int tot = 0;
for (r = 0; r < rows; r++)
for (c = 0; c < COLS; c++)
tot += ar[r][c];
return tot;
}