C Program to Find the Sum of Natural Numbers using Recursion
Code:
#include <stdio.h> int Sum(int x); int Sum(int x) { if (x != 0) return x + Sum(x - 1); else return x; } int main() { int number; printf("Enter a number: "); scanf("%d", &number); printf("Sum of natural numbers is %d\n", Sum(number)); return 0; }
Output:
Enter a number: 5 Sum of natural numbers is 15
C Program to Find Factorial of a Number Using Recursion
Code:
#include <stdio.h> long int Fact(int n); long int Fact(int n) { if (n >= 1) return n * Fact(n - 1); else return 1; } int main() { int n; printf("Enter a number: "); scanf("%d", &n); printf("Factorial is %ld\n", Fact(n)); return 0; }
Output:
Enter a number: 5 Factorial is 120
C Program to Find G.C.D Using Recursion
Code:
#include <stdio.h> int GCD(int number1, int number2); int GCD(int number1, int number2) { if (number2 != 0) return GCD(number2, number1 % number2); else return number1; } int main() { int number1, number2; printf("Enter first number: "); scanf("%d", &number1); printf("Enter second number: "); scanf("%d", &number2); printf("G.C.D is %d\n", GCD(number1, number2)); return 0; }
Output:
Enter first number: 8 Enter second number: 4 G.C.D is 4
C program to Reverse a Sentence Using Recursion
Code:
#include <stdio.h> void Rev(); void Rev() { char ch; scanf("%c", &ch); if (ch != '\n') { Rev(); printf("%c", ch); } } int main() { printf("Enter sentence: "); Rev(); printf("\n"); return 0; }
Output:
Enter sentence: Welcome To Codedec cededoC oT emocleW
C program to calculate the power using recursion
Code:
#include <stdio.h> int power(int number1, int number2); int power(int A, int n) { if (n != 0) return (A * power(A, n - 1)); else return 1; } int main() { int A, n, value; printf("Enter a number: "); scanf("%d", &A); printf("Enter power value: "); scanf("%d", &n); value = power(A, n); printf("Desired value is %d\n", value); return 0; }
Output:
Enter a number: 5 Enter power value: 3 Desired value is 125