having a n by n square matrix calculate the sum of prime elements C -


i have "having n n square matrix calculate sum of prime elements main diagonal".

i tried this:

#include<stdio.h>  int main(){    int a[10][10],i,j,sum=0,m,n;    printf("\nenter rows , columns: ");   scanf("%d %d",&m,&n);    printf("\nenter elements: ");   for(i=0;i<m;i++)       for(j=0;j<n;j++)            scanf("%d",&a[i][j]);   printf("\nthe matrix is\n");    for(i=0;i<m;i++){       printf("\n");       for(j=0;j<m;j++){       printf("%d\t",a[i][j]);       }  }  for(i=0;i<m;i++){      for(j=0;j<n;j++){           if(i==j)               sum=sum+a[i][j];      }  }  printf("\n\nsum of diagonal elements: %d",sum);   return 0; } 

if it's fine how calculate sum of prime elements main diagonal? thanks!

you should check whether diagonal element prime or not.for should write separate function.

for(i=0;i<m;i++){  for(j=0;j<n;j++){       if(i==j && isprime(a[i][j]))           sum=sum+a[i][j];  } }  int isprime(int a) {     for(int i=2;i<=a/2;i++)        if(a%i==0)           return 0;     return 1; } //note can optimize above loop running till sqrt(a) 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -