Here's a C program to find sum of all the elements of a matrix using For Loops and Nested Loops with output and explanation.
# include <stdio.h> # include <conio.h> void main() { int mat[10][10] ; int i, j, row, col, sum = 0 ; clrscr() ; printf("Enter the order of the matrix : ") ; scanf("%d %d", &row, &col) ; printf("\nEnter the elements of the matrix : \n\n") ; for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) scanf("%d", &mat[i][j]) ; for(i = 0 ; i < row ; i++) for(j = 0 ; j < col ; j++) sum = sum + mat[i][j] ; printf("\nThe sum of the elements in the matrix is : %d", sum) ; getch() ; }
Output of above program -
Enter the order of the matrix : 3 3
Enter the elements of the matrix :
1 2 3
4 5 6
7 8 9
The sum of the elements in the matrix is : 45
Explanation of above program -
In this program we’ve several variables. Let’s first
understand the purpose of each variable –
- mat[10][10] – is a two dimensional integer array representing a matrix containing 10 rows (first index) and 10 columns (second index). This is how matrices are represented in C.
- i and j – are loop variables of two different for loops where i points to the rows and j points to the columns of our matrix.
- row and col – are the number of rows and columns respectively. These values are entered by user.
- sum – holds the sum of all the elements of our matrix mat[10][10]. It’s value is initialized to 0.
Now, the program first asks the user to enter the order of
the matrix i.e. number of rows and columns and stores these values in row and
col variables respectively. Next step is to enter the values in our matrix. To
do this, we use a nested for loop where the outer for loop (loop variable i)
points to every row of the matrix and inner for loop (loop variable j) points
to every column of the matrix. (See this program to understand How to Enter and Print Values in a Matrix)
Once you have entered the values in your matrix it’s time to
calculate the sum of all elements in the matrix. For this, we again use another
nested for loop like we did before. Inside this nested for loop we add each
element to the value of variable sum and update its value. After this nested
loop terminates, we have the sum of all elements of our matrix “mat[10][10]”
and print its value.
Hello There,
Brilliant article, glad I slogged through the C Programming Tutorial it seems that a whole lot of the details really come back to from my past project.
write a c program that finds number of any paragraph and sentence in a text.
I'm new at this and I really need to do this.
Follow my new blog if you interested in just tag along me in any social media platforms!
Thank you,
Heena
Can i get tracing of a program