What is Recursion? Wap Using Recursion to Find the Sum of Array Elements of Size N.
Advertisements
प्रश्न
What is recursion? WAP using recursion to find the sum of array elements of size n.
Advertisements
उत्तर
1. Recursion: A function that calls itself is called as recursive function and this technique is called as recursion.
2. A recursive function must definitely have a condition that exits from calling the function again.
3. Hence there must be a condition that calls the function itself if that condition is true.
4. If the condition is false then it will exit from the loop of calling itself again.
Program:
#include<conio.h>
#include <stdio.h>
#define MAX_SIZE 100
int sum(int arr[], int start, int len);
void main()
{
int arr[MAX_SIZE];
int N, i, sumof_array;
clrscr();
printf("Enter size of the array: ");
scanf("%d", &N);
printf("Enter elements in the array: ");
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
sumof_array = sum(arr, 0, N);
printf("Sum of array elements: %d", sumof_array);
getch();
}
int sum(int arr[], int start, int len)
{
if(start >= len)
return 0;
return (arr[start] + sum(arr, start + 1, len));
}
Output:
Enter size of the array: 10
Enter elements in the array: 1 2 3 4 5 6 7 8 9 10
Sum of array Elements: 55APPEARS IN
संबंधित प्रश्न
What is recursion? Write a program to find xy using recursion.
What are advantages and disadvantages of recursion? Comment on conditions to be considered while writing a recursive function. Write a program to print Fibonacci series up to N terms using a recursive function.
Explain recursive function. Write a program to find the GCD of a number by using recursive function.
