Q6 Write a \"C\" program that calls a function to add two matrices (matrix = two
ID: 3607568 • Letter: Q
Question
Q6
Write a "C" program that calls a function to add two matrices (matrix = two-dimensional array).
You decide on the size of the matrix and the elements of the matrices.
The main program should create and populate the matrices with non-zero values. The function should perform a matrix addition and assign the result to another array. The function should be flexible enough to work with any array size and the sizes communicated to the function from the main function.
After the function call, the main program should print the array with the initial values followed by the result of the addition as shown below.
Initial values
3 1 2
7 8 9
6 5 1
3 4 5
Result
9 6 3
10 12 14
Use as many variables and arrays as needed.
Provide restriction so that the original array passed to it cannot be modified by the function.
Print using %2d to streamline the output
Q6
Write a "C" program that calls a function to add two matrices (matrix = two-dimensional array).
You decide on the size of the matrix and the elements of the matrices.
The main program should create and populate the matrices with non-zero values. The function should perform a matrix addition and assign the result to another array. The function should be flexible enough to work with any array size and the sizes communicated to the function from the main function.
After the function call, the main program should print the array with the initial values followed by the result of the addition as shown below.
Initial values
3 1 2
7 8 9
6 5 1
3 4 5
Result
9 6 3
10 12 14
Use as many variables and arrays as needed.
Provide restriction so that the original array passed to it cannot be modified by the function.
Print using %2d to streamline the output
Explanation / Answer
#include <stdio.h>
#define ROW_SIZE 2
#define COLUMN_SIZE 3
void addition(const int a[][COLUMN_SIZE], const int b[][COLUMN_SIZE],int c[][COLUMN_SIZE]) {
int i,j;
for(i=0;i<ROW_SIZE; i++) {
for(j=0;j<COLUMN_SIZE;j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
}
int main()
{
int a[ROW_SIZE][COLUMN_SIZE], b[ROW_SIZE][COLUMN_SIZE], c[ROW_SIZE][COLUMN_SIZE];
int i,j;
printf("Enter the first array elements: ");
for(i=0;i<ROW_SIZE; i++) {
for(j=0;j<COLUMN_SIZE;j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the second array elements: ");
for(i=0;i<ROW_SIZE; i++) {
for(j=0;j<COLUMN_SIZE;j++) {
scanf("%d", &b[i][j]);
}
}
addition(a,b,c);
printf("Addition of array elements: ");
for(i=0;i<ROW_SIZE; i++) {
for(j=0;j<COLUMN_SIZE;j++) {
printf("%4d", c[i][j]);
}
printf(" ");
}
return 0;
}
Output:
3 1 2
7 8 9
6 5 1
3 4 5
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.