A program to declare a two dimensional array of size 4 x 4, initialized in column major order, which does the desired operation according to the choice of the user. The various operations are:
            a) Displays the sum of both the diagonals.
            b) Displays the sum of all even elements.
            c) Displays the sum of all odd elements.

 

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

int a[4][4],i,j,sum=0;

void sum_of_diagonals()
{
for(i=0;i<4;i++)
sum=sum+a[i][i];
cout<<"\nSum of first diagonal:"<<sum<<endl;
sum=0;
j=3;
for(i=0;i<4;i++)
{
sum=sum+a[i][j];
j--;
}
cout<<"Sum of second diagonal:"<<sum<<endl;
}

void sum_of_even_elements()
{
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(a[i][j]%2==0)
sum=sum+a[i][j];
}
}
cout<<"\nSum of even elements in the array: "<<sum<<endl;
}

void sum_of_odd_elements()
{
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(a[i][j]%2!=0)
sum=sum+a[i][j];
}
}
cout<<"\nSum of odd elements in the array: "<<sum<<endl;
}

void main()
{
 clrscr();
 int x=1,ch;
 cout<<"Enter elements of array in coloumn major order:"<<endl;
 for(i=0;i<4;i++)
  { 
   for(j=0;j<4;j++)
    {
     cout<<"Enter element no."<<x<<": ";
     cin>>a[j][i];
     x++;
    }
   }

 clrscr();
    
 do
  {
   cout<<"1. Sum of the diagonals of the array."<<endl;
   cout<<"2. Sum of all the even elements of the array."<<endl;
   cout<<"3. Sum of all the odd elements of the array."<<endl;
   cout<<"4. Exit."<<endl;
   cout<<"Enter your choice: ";
   cin>>ch;

   switch(ch)
    {
     case 1: {
                 sum_of_diagonals();
                 break;
                }
     case 2: {
                 sum_of_even_elements();
                 break;
                }
     case 3: {
                 sum_of_odd_elements();
                 break;
                }
     case 4: {
                 break;
                }
     default: {
                  cout<<"\nWrong choice entered."<<endl;
                  break;
                 }
    }
   cout<<endl;
  }
 while(ch!=4);
}

 

< Back