WRITE THE FOLLOWING PROGRAM IN C (NOT C++ OR JAVA) Write a C program that calls
ID: 3607478 • Letter: W
Question
WRITE THE FOLLOWING PROGRAM IN C (NOT C++ OR JAVA)
Write a C program that calls a function to multiply a matrix (two dimensional array).
The main program should ask the user to enter an integer that will be used as the matrix “adder” and then call the function. The function should perform a matrix increment (every element of the array is incremented by the same value) and assign the result to another array. The function should be flexible enough to work with any array size and “adder”, 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 multiplied values as shown below.
Use as many variables and arrays as needed. When initializing the array, use the initial values shown in the output.
Provide restriction so that the original array passed to it cannot be modified by the function.
Expected input / output.
Enter adder: 2
Initial values
5 2 7
1 6 3
After adding by 2
7 4 9
3 8 5
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int** addToMatrix(int *a, int n, int m, int addr) {
int i, j;
int **newMatrix = (int **)malloc(n * sizeof(int *));
for (i=0; i < n; i++)
newMatrix[i] = (int *)malloc(m * sizeof(int));
for (i = 0; i < n; i++) {
for(j = 0; j < m; j++) {
newMatrix[i][j] = addr + *((a+i*m) + j);
}
}
return newMatrix;
}
int main()
{
int matrix[2][3] = {5,2,7, 1,6,3};
printf("Enter adder: ");
int adder;
scanf("%d", &adder);
int **newmatrix = addToMatrix((int *)matrix, 2, 3, adder);
printf("Initial values ");
int i, j;
for (i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf(" ");
}
printf("After adding by %d ", adder);
for (i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", newmatrix[i][j]);
}
printf(" ");
}
return 0;
}
Sample run
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.