Write C programs that use both recursive
and non-recursive functions
- To find the
factorial
of a given integer. - To find the
GCD
(greatest common divisor) of two given integers.
Description:
Factorial of a number is nothing but the multiplication of numbers from a given number to 1 Ex: 5! =5*4*3*2*1= 120
i) To find the factorial of a given integer.
Algorithm:
Step 1: Start Step 2: Read n value as integer Step 3: Call function factorial (int n) Step 4: End Call function factorial(int n) begin if (n = 0) return 1; else return (n * factorial(n - 1)); end
Program:
#include <stdio.h> #include <conio.h> void main() { int n, a, b; clrscr(); printf("Enter any number\n"); scanf("%d", &n); a = recfactorial(n); printf("The factorial of a given number using recursion is %d \n", a); b = nonrecfactorial(n); printf("The factorial of a given number using nonrecursion is %d ", b); getch(); } int recfactorial(int x) { int f; if(x == 0) { return(1); } else { f = x * recfactorial(x - 1); return(f); } } int nonrecfactorial(int x) { int i, f = 1; for(i = 1;i <= x; i++) { f = f * i; } return(f); }
Input & Output:
Enter any number 5 The factorial of a given number using recursion is 120 The factorial of a given number using nonrecursion is 120
ii) To find the GCD (greatest common divisor) of two given integers
Algorithm:
Step 1: Start Step 2: Read a, b values as integers Step 3: Call function gcd (a, b) and assign it to res Step 4: Print res Step 5: Stop Called function gcd (a, b) begin while(v != 0) begin temp ← u MOD v; u ← v; v ← temp; end return(u); end
Program:
#include <stdio.h> #include <conio.h> void main() { int a, b, c, d; clrscr(); printf("Enter two numbers a, b\n"); scanf("%d%d", &a, &b); c = recgcd(a, b); printf("The gcd of two numbers using recursion is %d\n", c); d = nonrecgcd(a, b); printf("The gcd of two numbers using nonrecursion is %d", d); getch(); } int recgcd(int x, int y) { if(y == 0) { return(x); } else { return(recgcd(y, x % y)); } } int nonrecgcd(int x, int y) { int z; while(x % y != 0) { z = x % y; x = y; y = z; } return(y); }
Input & Output:
Enter two numbers a, b 3 6 The gcd of two numbers using recursion is 3 The gcd of two numbers using nonrecursion is 3
-
UpdatedDec 25, 2014
-
Views59,530
Write a C program to find the roots of a quadratic equation
.
Write a C program to count the lines, words and characters in a given text.
Write a C program to find the sum of individual digits of a positive integer.
Write a C program, which takes two integer operands and one operator from the user, performs the operation and then prints the result. (Consider the operators +,-,*, /, % and use switch statement
)
Write a C program to generate all the prime numbers
between 1 and n, where n is a value supplied by the user.
Write C programs that use both recursive
and non-recursive functions
- To find the
factorial
of a given integer. - To find the
GCD
(greatest common divisor) of two given integers.