Course Content
Detailed Content of Programming in C
0/1
Introduction
0/1
Structure of C program
0/1
Answers of ‘C’ Pointers Programs
0/1
About Lesson

Program to Find the Sum of Elements in a 2D Array.

#include <stdio.h>

// Function to calculate the sum of elements in a 2D array
int calculateArraySum(int arr[][3], int rows, int cols) {
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum += arr[i][j];
}
}
return sum;
}

int main() {
int rows, cols;

// Taking input for the number of rows and columns
printf(“Enter the number of rows: “);
scanf(“%d”, &rows);

printf(“Enter the number of columns: “);
scanf(“%d”, &cols);

int array[rows][cols];

// Taking input for array elements
printf(“Enter %d x %d elements:n”, rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf(“%d”, &array[i][j]);
}
}

// Calling the function to calculate the sum and printing the result
int sum = calculateArraySum(array, rows, cols);
printf(“Sum of elements in the 2D array: %dn”, sum);

return 0;
}