Write C Program to Find the Sum of Each Row and Column of a 2x2 Matrix - 15 marksSample InputEnter the co-efficients of the matrix23 4580 97
Question
Write C Program to Find the Sum of Each Row and Column of a 2x2 Matrix
- 15 marks
Sample Input
Enter the co-efficients of the matrix
23 45
80 97
Solution
C Program to Find the Sum of Each Row and Column of a 2x2 Matrix
Below is a sample C program that reads the coefficients of a 2x2 matrix from the user and calculates the sum of each row and each column.
#include <stdio.h>
int main() {
int matrix[2][2];
int rowSum[2] = {0, 0};
int colSum[2] = {0, 0};
// Input the coefficients of the matrix
printf("Enter the coefficients of the 2x2 matrix:\n");
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Calculate the sum of each row and column
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
rowSum[i] += matrix[i][j];
colSum[j] += matrix[i][j];
}
}
// Output the sums
printf("Row sums:\n");
for(int i = 0; i < 2; i++) {
printf("Sum of row %d: %d\n", i + 1, rowSum[i]);
}
printf("Column sums:\n");
for(int j = 0; j < 2; j++) {
printf("Sum of column %d: %d\n", j + 1, colSum[j]);
}
return 0;
}
Explanation of the Program
- Input: The program first prompts the user to enter the coefficients of the 2x2 matrix.
- Calculation: Using nested loops, it calculates the sum of each row and each column by updating the respective
rowSum
andcolSum
arrays. - Output: Finally, it prints the sums of each row and column.
Final Note
Make sure to compile the program using a C compiler and provide the input in the specified format.
Similar Questions
Given is a matrix with elements of the data type double. In order to sum up all matrix elements of the first column, a nested loop has to be used.
The transpose of a matrix in C can be efficiently computed using:Two nested loopsRecursionPointersmemcpy() function
Write a java program to perform matrix multiplicationinput:m-no. of rowsn-no.of columsmatrix1=[]matrix2=[]output:matrix3=[]
Write a program to convert the given graph from matrix representation to linked list representation
Calculate the run-time efficiency of the following program segment:for (i = 1; i <= n; i++)printf("%d ", i);
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.