Write a user-defined function in C++ to find and display the sum of both the diagonal
elements of a two-dimensional array MATRIX [6] [6] containing integers.
I did this....
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int i,j,a[6][6], sum=0;
cout<<" Enter values in the matrix";
for(i=0;i<6;i++)
{ for(j=0;j<6;j++)
{ cout<<" Enter value for a["<<i<<"]["<<j<<"]";
cin>>a[i][j];
if(i==j||(i+j)==6)
sum+=a[i][j];
}
cout<<"Sum is: "<<sum;
getch();
}
Is it correct?
I know it is ..
Any better way doing that?
Yes. Don't include <conio.h>, make sure you include <iostream> and NOT <iostream.h>, don't use clrscr() (it's not even needed here), use cin.ignore(unsigned(-1), '\n') instead of getch(), and use proper code indenting.
if(i==j||(i+j)==6)
Shouldn't this be if(i==j||(i+j)==5) ?
>Write a user-defined function in C++ to find and display the sum of both the diagonal
>elements of a two-dimensional array MATRIX [6] [6] containing integers.
If you are actually going to write a function, write it with just one loop.
1 2 3 4 5 6 7 8 9
enum { N = 6 } ;
typedefint array_type[N][N] ;
int sum_diagonals( const array_type& array )
{
int sum = 0 ;
for( int i = 0 ; i<N ; ++i ) sum += array[i][i] + array[i][N-i-1] ;
return sum ;
}
Awesome...
Now got it.
@Albatross: I cant at this moment but will do after two months when my Course completes and will be learning a lot from all of you here when in vacations...
Thank you to all of you.