To find the sum of even numbers of an array using recursion.
/* to calculate
the sum of even numbers using recursion */
#include<stdio.h>
#include<malloc.h>
int
evensumrec(int *a,int n);
int main()
{
int *a,i,n,sum;
printf("\n
Enter the number of elements:");
scanf("%d",&n);
a=(int
*)malloc(n*sizeof(int));
printf("\n
Enter the elements of the array:");
for(i=0;i<n;i++)
scanf("%d",(a+i));
sum=evensumrec(a,n-1);
printf("\n
Sum of even numbers is %d",sum);
return 0;
}
int
evensumrec(int *a, int n)
{
if(*(a+n)%2==0)
{
if(n>=0)
return (*(a+n)+evensumrec(a,n-1));
else
return 0;
}
else
return (evensumrec(a,n-1));
}
Input/Output:
Enter the number of elements:7
Enter the elements of the array:23
4
-6
13
17
66
0
Sum of even numbers is 64
No comments:
Post a Comment