0% found this document useful (0 votes)
18 views2 pages

Recursion Assignment Programs

The document contains C programming assignments focused on recursion, including programs to calculate the factorial of a number, find the GCD of two numbers, generate Fibonacci series, and solve the Tower of Hanoi problem. Each program includes the necessary code and prompts for user input. The assignments aim to enhance understanding of recursion in C programming.

Uploaded by

mp1121451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views2 pages

Recursion Assignment Programs

The document contains C programming assignments focused on recursion, including programs to calculate the factorial of a number, find the GCD of two numbers, generate Fibonacci series, and solve the Tower of Hanoi problem. Each program includes the necessary code and prompts for user input. The assignments aim to enhance understanding of recursion in C programming.

Uploaded by

mp1121451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

C Programming Assignment - Recursion

Q1) Write a C program for factorial of number using recursion.


#include <stdio.h>
int factorial(int n) {
if(n == 0) return 1;
return n * factorial(n - 1);
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Factorial of %d is %d\n", n, factorial(n));
return 0;
}

Q2) Write a C program for GCD of numbers using recursion.


#include <stdio.h>
int gcd(int a, int b) {
if(b == 0) return a;
return gcd(b, a % b);
}
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));
return 0;
}

Q3) Write a C program for Fibonacci of numbers using recursion.


#include <stdio.h>
int fibonacci(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n, i;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: ");
for(i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}

Q4) Write a C program for the tower of Hanoi using recursion.


#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 number of disks: ");
scanf("%d", &n);
towerOfHanoi(n, 'A', 'C', 'B');
return 0;
}

You might also like