codescracker


c

C Program to Find Sum of all Elements in a Matrix



« C Tutorial C Examples »

Sum of All Matrix Elements in C

The question is Write a C program that takes 9 elements/numbers of 3*3 matrix as input from user at run-time and calculate the sum of all the matrix elements to print it out on the output screen. Let's take a look at the program:

C Programming Code to Find Sum of Matrix Elements

Here is the program that calculates the sum of all 9 elements of 3*3 matrix and print the summation result as output:

// Write a program in C to input any 3x3 matrix
// and find sum of all the elements
// -------codescracker.com--------

#include<stdio.h>
#include<conio.h>
int main()
{
	int mat[3][3], i, j, sum;
	sum = 0;
	printf("Enter all 9 elements of 3*3 Matrix:-\n");
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			scanf("%d", &mat[i][j]);
		}
	}
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			sum = sum + mat[i][j];
		}
	}
	printf("\nSum of all elements = %d", sum);
	getch();
	return 0;
}

The program is written in Code::Blocks IDE, therefore after build and run, you will get the output as shown in the sample given here. Below is the first screenshot:

c program sum of all elements in matrix

Enter all the 9 elements and press enter key, here is the second screenshot of the sample run:

sum of elements in matrix c

Here are some of the main steps involved in above program:

  1. Take all 9 elements as input and initialize to the matrix one by one
  2. The 3*3 matrix means, it has 3 rows and 3 columns
  3. We have to use two for loops, outer one is for rows, and inner one is for column
  4. In this way, the first element is initialized to mat[0][0], the second element is initialized to mat[0][1], and the third element is initialized to mat[0][2], ....., the seventh element is initialized to mat[2][0], the eigth element is initialized to mat[2][1], and the ninth element is initialized to mat[2][2]
  5. After getting all the 9 elements as input, create another two for loop to sum-up all the elements one by one
  6. Finally print out the value of sum variable. Never forgot to initialize 0 to sum variable before start calculating sum of all the matrix elements

Here is the modified version of the above program. In this case, we have put the expression that calculates sum of all elements inside the loop in which we are taking 9 inputs from the user as 9 elements of 3*3 matrix.

// Write a program in C to input any 3x3 matrix
// and find sum of all the elements
// ------codescracker.com--------

#include<stdio.h>
#include<conio.h>
int main()
{
	int mat[3][3], i, j, sum;
	sum = 0;
	printf("Enter Matrix elements:-\n");
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			scanf("%d", &mat[i][j]);
			sum = sum + mat[i][j];
		}
	}
	printf("\nSum of all elements = %d", sum);
	getch();
	return 0;
}

You will get the same output as in above program.


« C Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test