How to calculate the sum of each row in a two-dimensional array in C language?
To find the sum of each row in a two-dimensional array, you can use nested loops to iterate through each row and calculate the sum. Here is an example code:
#include <stdio.h>
int main() {
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int arr[rows][cols];
// Input values into the array
printf("Enter the elements of the array:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &arr[i][j]);
}
}
// Calculate the sum of each row
for (int i = 0; i < rows; i++) {
int sum = 0;
for (int j = 0; j < cols; j++) {
sum += arr[i][j];
}
printf("Sum of row %d: %d\n", i+1, sum);
}
return 0;
}
In this example, we first input the number of rows and columns in a 2D array, followed by inputting the elements of the array. Then, we use a nested loop to iterate through each row, calculate the sum of each row, and finally output the sum of each row.