Note: Memory allocatedin heap will not be released
automatically, it’s programmer responsibility to release
that memory
21.
Recursion
• Recursion meansfunctions call itself until some conditions to be
satisfy.
• This technique provides a way to break complicated problems down
into simple problems which are easier to solve.
• Adding two numbers together is easy to do, but adding a range of
numbers is more complicated.
• In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding
two numbers:
22.
GCD
• The GCDis a mathematical term for the Greatest Common Divisor of
two or more numbers.
• It is the Greatest common divisor that completely divides two or
more numbers without leaving any remainder.
• Therefore, it is also known as the Highest Common Factor (HCF) of
two numbers.
• For example, the GCD of two numbers, 20 and 28, is 4 because both
20 and 28 are completely divisible by 1, 2, 4 (the remainder is 0), and
the largest positive number among the factors 1, 2, and 4 is 4.
23.
GCD
#include <stdio.h>
int gcd(inta, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int main() {
int a = 56, b = 98;
printf("GCD of %d and %d = %dn", a, b, gcd(a, b));
return 0;
}
24.
Factorial
#include <stdio.h>
int factorial(intn) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d = %dn", num, factorial(num));
return 0;
}
25.
Fibonacci series
• TheFibonacci series is a numerical sequence achieved through
specific programming constructs.
• The series, conventionally, commences from 0 and 1, with
subsequent numbers calculated as the sum of the prior two.
• For instance, a Fibonacci series beginning with 0 and 1 appears as
follows:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
26.
Tower of Hanoi
•Tower of Hanoi is a mathematical puzzle where we have three rods
and n disks.
• The objective of the puzzle is to move the entire stack to another
rod.
obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks
and placing it on top of another stack i.e. a disk can only be moved if
it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.