Time spent here:

Saturday, 18 June 2016

PRINT THE SUM OF DIAGONALS

Problem statement:
Print the sum of diagonals.
 
E.g.:
Consider the following matrix for n=3
7 8 9
6 1 2
5 4 3
the sum of the diagonal elements is 25 
 
Input: 
5
 
Output:
101

Code:
#include <stdio.h>
int main()
{
    int n,sum,count,itr,i,val;
    scanf("%d",&n);
    if(n%2==0)
    {
                val=1;itr=2; sum=0;count=0;
    }
     else
     {
       val=2;itr=3; sum=1;count=1;
     }
     
      
      
        while(itr <= n)
        {
            for(i=0;i<4;i++)
              {
                 count=count+val;
                 sum=sum+count;
              }
        itr=itr+2;val+=2;
        }
        printf("%d\n",sum);
   
    return 0;
}

OUTPUT:


 

No comments:

Post a Comment