In: Computer Science
What would the output be for the following program code segment?
#define ROWS 3
#define COLS 3
void addCoulmns(int arr[][COLS],int Sum[COLS]);
int main(void)
{
int array[ROWS][COLS] = {{ 10, 35, 23 },
{ 5, 4, 57 },
{ 4, 7, 21 }};
int ColSum[ROWS];
int rows;
int columns;
addCoulmns(array,ColSum);
for (columns = 0; columns < COLS - 1; columns++)
printf("%d\n",ColSum[columns]);
return(0);
}
void addCoulmns(int arr[][COLS],int Sum[COLS])
{
int row;
int col;
for (col = 0; col < COLS - 1; col++)
{
Sum[col] = 0;
for (row = 0; row < ROWS - 1; row++)
Sum[col] += arr[row][col];
}
return;
}
Output:
15
39
Short Explanation:
In main function we are calling a function called addCoulmns(array,ColSum) here ColSum is a array of integer
Inside the addCoulmns function there is a for loop which iterate till ROWS-1 which means 3-1=2, So in first iteration Sum[col] which is equivalent to ColSum 1st iteration of outer loop and 1st of inner loop row=0,col=0 so Sum[0]=arr[0][0]+ Sum[0] so Sum[0]=10+0 //(0 because we have initialize Sum[]=0 at first). 2nd iteration of inner loop row=1 col=0 Sum[0]=arr[1][0]+Sum[0] which is Sum[0]=5+10=15
Therefore Sum[0]=15 and now 2nd iteration of outer loop 1st iteration of inner loop will be row=0 col=1 Sum[1]=arr[0][1]+Sum[1] which is Sum[1]=35+0 so Sum[1]=35 now 2nd iteration in inner for loop row=1 col=1 , Sum[1]=arr[1][1]+Sum[1] which is Sum[1]=4+35=39
Sum[0]=15 Sum[1]=39
Inside main() again
COLS has value 3 we are iterating in for loop which is in main up to COLS-1 which means 3-1=2. So the loop will iterate 2 times, Inside for loop we have print statement which prints a value which is most probably integer printing value of array named ColSum which is equivalent to Sum so ColSum has value 15 39
Col[0]=15 Col[1]=39