I was doing a program to print sum of 2 matrixes and I took a 3rd variable 'sum' to store the sum of 2 matrixes. But the output was wrong. Then I used another array to store the sum of those 2 matrixes and it ran perfectly fine. I asked my teacher and he also told me store it in an array. But I want to understand why storing in sum variable won't work. Please explain .
-
2Welcome to Stack Overflow. Please take the time to go through the The Tour and refer to the material from the Help Center on what and how you can ask here.It's specially important to post a minimal reproducible example.– R SahuCommented Aug 21, 2018 at 5:01
-
Are you sure that your teacher didn't tell you to use a pointer to the integer? Because the parameter type for a pointer to one int and to an array of ints is the same you may have gotten confused.– PeterTCommented Aug 21, 2018 at 5:26
-
2It is unclear what you exactly tried to achieve. The sum of two matrixes usually is a matrix or cannot be calculated at all. The sum of all the entries in one matrix can of course be added up in a single variable, then going on with a second matrix is no a problem. If you do that and the output is wrong, you simply made a mistake. To find that mistake we would have to see the code. Please also explain how you know that the output is wrong. What is the wrong output? What would be the correct output? For what input? Giving that information is called making a minimal reproducible example.– YunnoschCommented Aug 21, 2018 at 5:45
Add a comment
|
1 Answer
#include <stdio.h>
#define ROW 2
#define COL 2
int main(){
int sum = 0, i, j;
int arr1[ROW][COL] = {1, 2, 3, 4}, arr2[ROW][COL] = {4, 3, 2, 1};/* You can do dynamic allocation too with malloc */
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++){
sum += (arr1[i][j] + arr2[i][j]);
}
}
printf("sum: %d\n",sum);
return 0;
}