0

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 .

3
  • 2
    Welcome 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 Sahu
    Commented 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.
    – PeterT
    Commented Aug 21, 2018 at 5:26
  • 2
    It 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.
    – Yunnosch
    Commented Aug 21, 2018 at 5:45

1 Answer 1

0
#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;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.