0
2.5kviews
What do you mean by recursion? Write a program, which will accept 2 nos from user say x and y. and calculate xy. Program should make use of recursion. If x is 3 and y is 4 then output should by $3^4$
1 Answer
0
59views

Recursive Function:

  • A function that calls itself is called as recursive function.
  • A recursive function must definitely have a condition that exists from calling the function again.
  • Hence there must be a condition that calls the function itself if that condition is true.
  • If the condition is false then it will exit from the loop of calling itself again.

Algorithm:

Main () Function:

  • Start.
  • Print “Enter values of x and y”.
  • Input x, y.
  • n = CALL exponential (arguments: x, y)
  • Print n.
  • Stop.

Exponential (parameters: x, y)

  • Start.
  • If y=1, then return x.
  • Else return(x*CALL exponential(arguments: x, y-1))
  • Stop.

Program:

#include <stdio.h>
#include <conio.h>
int main() {
    int x, n, y;
    int exponential(int x, int y);

    printf("Enter the values of x and y:");
    scanf("%d%d", &x, &y);

    n = exponential(x,y);

    printf("The value of x raise to y is %d", n);
    getch();
}
int exponential(int x, int y) {
    if(y==1)
    return x;
    else
    return (x*exponential(x, y-1));
}

Output:

Enter the value of x and y: 3 4

The value of x raise to y is 81

Explanation:

  • In this program, to get value of XY, we just multiply “X” with XY-1.
  • This is continued until we get X1.
  • This is done by the recursive function “exponential”.
  • It checks the value of the index, if it is equal to 1, then it returns just the value of “X”.
  • Else it passes the value of XY-1 by calling itself i.e. recursive function.
Please log in to add an answer.