Monday 30 January 2017

Sum of array elements using recursion in C

What is a recursive solution to summing up a list of numbers? First you should note that the sum of [2 13 4 25 66 71 82 91]) is equal to 2 + sum of [ 13 4 25 66 71 82 91]

#include <stdio.h>
int sum(int *a,int index,int n)
{
if(index == n)
return 0;
return(a[index]+sum(a,index+1,n));
}
main()
{
int n,i,a[100];
printf("enter size of array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("array sum =%d",sum(a,0,n));
}

(OR)

#include <stdio.h>
int sum(int *a,int n)
{
if(n<=0)
return 0;
return(*a+sum(++a,--n));
}
main()
{
int n,i,a[100];
printf("enter size of array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("array sum =%d",sum(a,n));
}


Write a C program to generate fibonacci series upto n terms using recursion
#include <stdio.h>
int fib(int n)
{
if(n == 0 || n ==1)
return n;
return(fib(n-1)+fib(n-2));
}
main()
{
int n,i;
printf("enter number of terms\n");
scanf("%d",&n);
for(i=0;i<n;i++)
printf("\n %d\t",fib(i));
}

No comments:

Post a Comment