Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Array

2D Array

Patterns

Excersises


Sum of All Elements in 2D array


Here's an example program in C to calculate the sum of all elements in a 2D array

Example : sum_of_all_elements_2darray.c
#include <stdio.h>

int main() {
  int rows, cols, sum = 0;
  
  printf("Enter the number of rows: ");
  scanf("%d", &rows);
  printf("Enter the number of columns: ");
  scanf("%d", &cols);
  
  int array[rows][cols];
  
  printf("Enter the elements of the array:\n");
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("Enter element at [%d][%d]: ", i, j);
      scanf("%d", &array[i][j]);
      sum += array[i][j];
    }
  }
  
  printf("The sum of all elements in the 2D array is: %d\n", sum);
  
  return 0;
}

Output:

Enter the number of rows: 2
Enter the number of columns: 2
Enter the elements of the array:
Enter element at [0][0]: 1
Enter element at [0][1]: 2
Enter element at [1][0]: 3
Enter element at [1][1]: 4
The sum of all elements in the 2D array is: 10