Sunday, 31 August 2014

C++ program to find the sum of diagonal elements

C++ program to find the sum of diagonal elements : A simple C++ program which find the sum of diagonal element of matrices.There are two diagonal in a matrix primary diagonal and secondary diagonal, so this program first ask the choice about diagonal from user and then print the total.

C++ program to find the sum of diagonal elements



C++ program to find the sum of diagonal elements 


#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int i,s=0,j,r,c,ch,a[50][50];
cout<<"Entr Array Limit"<<endl;
cin>>r>>c;
if(r!=c)
cout<<"Wrong Choice"<<endl;
else
{
cout<<"Enter Array"<<endl;
  for(i=0;i<r;i++)
  {
   for(j=0;j<c;j++)
   {
   cin>>a[i][j];
   }
  }
cout<<"Enter Choice 1:main  2:Secondary"<<endl;
cin>>ch;
switch(ch)
{
case 1:
  for(i=0;i<r;i++)
  {
  s=s+a[i][i];
  }
cout<<"Sum = "<<s;
break;

case 2 :
j=c-1;
  for(i=0;i<r;i++)
  {
  s=s+a[i][j--];
  }
  cout<<"Sum = "<<s;
break;

default :
cout<<"Wrong Choice"<<endl;
break;

}
}
getch();
}