2 dimenstional array question. important

Jan 24, 2011 at 5:48am
/*
simple program for 2 arrays. I need to answer these questions and I am stuck;/

1)Use for loop structure to set the value of each element to the sum of its subscripts.
2)Write the necessary statements to output the values of the elements of this array with SIZE elements per line.

*/
#include <stdio.h>
#define SIZE 3
int sum_array(int array[][SIZE]);

int main(void)
{
int array[SIZE][SIZE] = {{1,2,3},
{4,5,6},
{6,7,8}};

// #1
int sum =0;

int i, j; //#2 total of 9 elements
for (i = 0; i <SIZE; i++)
{
for (j = 0; j<SIZE; j++)
printf("%d", array[i][j]);
}
sum=sum_array(array);
printf("\n\n%d", sum);
return 0;
}
int sum_array( int array[][SIZE])
{
int sum =0;

int i, j; //#2 total of 9 elements
for (i = 0; i <SIZE; i++)
{
for (j = 0; j<SIZE; j++)
sum+=array[i-1][j];
}

return sum;
}
Last edited on Jan 24, 2011 at 6:49am
Jan 24, 2011 at 11:00am
1)Use for loop structure to set the value of each element to the sum of its subscripts.

I assume subscripts are i and j (in a for loop) ? for(i ... ) for( j ... ) array[i][j] = i+j; ? not sure if they meant that..

2)Write the necessary statements to output the values of the elements of this array with SIZE elements per line.

You have written for (i = 0; i <SIZE; i++) for (j = 0; j<SIZE; j++) printf("%d", array[i][j]); but that prints all numbers in one line. If you want to split it into more lines, you have to printf("\n");. Do it once for every i : for( i ... ){ for( j ... ) print array[i][j]; print \n; }

Why in your sum() do you have a -1 in sum += array[i-1][j] ? This will cause an array out of bounds error.
Jan 24, 2011 at 7:17pm
perfect.

Thanks!
Topic archived. No new replies allowed.