Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Write a C program to read two 2D arrays (A and B) of nxn size (n rows and n columns), perform A+B, and display the output matrix.
Input: 3 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 // first element is size n, next nxn elements are matrix A, remaining nxn elements are matrix B.
A=  
 1 2 3
 4 5 6
 7 8 9
B=
 1 2 3
 4 5 6
 7 8 9
Output:  
2 4 6
8 10 12
14 16 18
 
4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

2 4 6 8
10 12 14 16
18 20 22 24
26 28 30 32

C
#include<stdio.h>
int main(){  
int n;
scanf("%d",&n);  
    int A[n][n];  
int B[n][n];  
int C[n][n];  
       for (int i=0; i<n; i++){="" 
for="" (int="" j="0;" j<n;="" j++){
="" scanf("%d",&a[i][j]);="" 
}="" i="0;" i<n;="" scanf("%d",&b[i][j]);="" 
}
for="" c[i][j]="A[i][j]+B[i][j];
printf("%d",C[i][j]);
if(j!=n-1)
" printf("="" ");
}="" 

printf("\n");
}="" 
}
What I have tried:

I have tried:

codes/mainc-5557-1609819708.8775194.c: In function 'main':
codes/mainc-5557-1609819708.8775194.c:25:19: error: 'i' undeclared (first use in this function)
     printf("%d",C[i][j]);
                   ^
codes/mainc-5557-1609819708.8775194.c:25:19: note: each undeclared identifier is reported only once for each function it appears in
codes/mainc-5557-1609819708.8775194.c:25:22: error: 'j' undeclared (first use in this function)
     printf("%d",C[i][j]);
                      ^
I am getting like this .
Posted
Updated 4-Jan-21 20:21pm
v2

You declared i in the for loop :
for (int i=0; i<n; i++) {
it needs to be declared outside the for loop, by where n is declared. The variable j also needs to be declared up there if they are to be accessed outside the for loop.

Also, I am surprised it is accepting your declarations of A, B, and C. I didn't think the C language allowed array variable declaration like that. I believe array dimensions must be a constant expressions.
 
Share this answer
 
Comments
CPallini 5-Jan-21 2:22am    
Both constructs are allowed in C99.
With a 'modern' (supporting C99) C compiler, and a bit of cheating you might write

C
#include <stdio.h>
  
int main()
{
  int n;
  scanf("%d", &n);
  for (int r=0; r<n; ++r)
  {
    for (int c=0; c<n; ++c)
    {
      int x;
      scanf("%d", &x);
      printf("%d ", 2*x);
    }
    printf("\n");
  }
  return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900