What is recursion? Write a C program to computer factorial using recursion.

7. B) What is recursion? Write a C program to computer factorial using recursion.

Answer:-

“Recursion is the repetitive process in which a function calls itself”

  • All recursive functions have two elements each call either solves one part of the problem or it reduces the size of the problem.
  • The statement that solves the problem is known as the base case.
  • The rest of the function is known as a general case.

C Program for Factorial of a number using Recursion

#include<stdio.h>; 
int fact(int);
void main()
{
int n,res;
printf(“enter the number to find its factorial\n”); 
scanf(“%d”,&n);
res=fact(n);
printf(“factorial of %d=%d”,n,res);
getch();
}
int fact(int n)
{
if(n==0) return 1;
else
return (n*fact(n-1));
}

C Program for Tower of Hanoi of a number using Recursion

/* Design, Develop and Implement a Program in C for the following Stack Applications
Solving Tower of Hanoi problem with n disks */


#include <stdio.h>

void towerOfHanoi(int n, char from, char to, char aux)
{
    if (n == 1)
    {
        printf("Move disk 1 from %c to %c\n", from, to);
        return;
    }
    towerOfHanoi(n - 1, from, aux, to);
    printf("Move disk %d from %c to %c\n", n, from, to);
    towerOfHanoi(n - 1, aux, to, from);
}

int main()
{
    int n;
    printf("Enter the number of disks: ");
    scanf("%d", &n);
    towerOfHanoi(n, 'A', 'C', 'B');
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *