Here's a C Program to find the sum of upper triangular elements of a matrix with explanation and example. This program uses Multidimensional Arrays, Nested Loops and For Loops.
Note: An upper triangular matrix is a square matrix in which the elements below the main diagonal are zero.
# include <stdio.h> # include <conio.h> void main() { int mat[10][10] ; int i, j, size, upper = 0; clrscr() ; printf("Enter size of the square matrix : ") ; scanf("%d", &size) ; printf("\nEnter the elements of the matrix : \n\n") ; for(i = 0 ; i < size ; i++) for(j = 0 ; j < size ; j++) scanf("%d", &mat[i][j]) ; printf("\nThe upper triangular matrix is : \n\n") ; for(i = 0 ; i < size ; i++) { for(j = 0 ; j < size ; j++) { if(i <= j) { printf("%d\t", mat[i][j]) ; upper = upper + mat[i][j] ; } else printf("\t") ; } printf("\n") ; } printf("\nThe sum of upper triangular elements is : %d\n",upper); getch() ; }
Output of the above program
Enter size of the square matrix : 3
Enter the elements of the matrix :
1 2 3
4 5 6
7 8 9
The upper triangular matrix is :
1 2 3
5 6
9
The sum of upper triangular elements is : 26
Explanation of above program
In this program, we have a square matrix mat of maximum size 10 x 10. The variables i and j are the loop variables that corresponds to the row and column of the matrix respectively. The variable size contains the size of the matrix.
First
the program asks the user to enter the size of the matrix and then
using a nested for loops the matrix is populated. Now to get the upper triangular matrix, the program prints only those values in the matrix for which i <= j or row number is less than or equal to column number. Also the sum of upper triangular elements is also calculated and stored in the variable upper.
Also take a look at: C Program to Find the Sum of Lower Triangular Matrix Elements
Hello There,
Hot! That was HOT! Glued to the C Programming Tutorial your proficiency and style!x
I am trying to load a few lines ( many strings separated by a space) from a text file and break them into string tokens and store it as structure fields. This functions should be performed by the load items(item); function.
However there is an anomaly. When I print the structure fields to check if they have been loaded properly, it turns out they are not!. when I print structure fields outside the load items(item); function the fields do not seem to be stored properly in the array.
Thank you very much and will look for more postings from you.
Many Thanks,
Madhu