0% found this document useful (0 votes)
12 views

2d Array

The document shows a C++ program to find and print the sum of the diagonal elements of a matrix. The program accepts the number of rows and columns from the user, inputs the matrix elements, and calculates the sum of the diagonal elements if the rows and columns are equal, outputting the result.

Uploaded by

Ayush Varshney
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

2d Array

The document shows a C++ program to find and print the sum of the diagonal elements of a matrix. The program accepts the number of rows and columns from the user, inputs the matrix elements, and calculates the sum of the diagonal elements if the rows and columns are equal, outputting the result.

Uploaded by

Ayush Varshney
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

C++ Program To Find & Print Sum Of Diagonal Elements Of Matrix.

/* Declaration Of Header Files */


# include <iostream.h>
# include <conio.h>
/* Start Of Main Program */
void main()
{
/* Declaration Of Variables */
int i, j, r = 0, c = 0;
int a [ 10 ][ 10 ];
clrscr();
/* Asking For The Input From User */
cout << " Enter Number Of Rows & Columns Of 2D Array [ Matrix ] : ";
cin >> r >> c ;
// Accepting Values Of 2D
cout << " Enter " <<
for ( i = 0; i < r;
{
for ( j = 0;
{
cin >>
}
}

Array [ Matrix ]
r * c << " Values for 2D Array : ";
i++ )
j < c; j++ )
a [ i ][ j ];

// Printing Values Of 2D Array [ Matrix ]


cout << " Values Of 2D Array [ Matrix ] Are : ";
for ( i = 0; i < r; i++ )
{
cout << " \n ";
for ( j = 0; j < c; j++ )
{
cin >> a [ i ][ j ];
}
}
/* Source Code For Computing Sum Of Diagonal Elements If & Only If Rows & Column
s Are Equal */
sum=0;
if(r==c)
{
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
if(i+j==0 || i+j==2 || i+j==4)
{
sum=sum+a[i][j];
}
}
}
/* Printing The Output Onto The Screen/Console */
cout<<"\n Sum Of Diagonal Elements Of Array Is : "<<sum;
}
else
{
cout<<" \n Addition Is Not Possible";

}
getch();
}
/* End Of Main Program */
Output :
Enter Order For Array A : 3 3
Enter 9 Values For Array :
1 2 3 4 5 6 7 8 9
Array
1 2
4 5
7 8

A Is :
3
6
9

Sum Of Diagonal Elements Of Array Is : 15

You might also like