W12 Programming Fundamentals
W12 Programming Fundamentals
FUNDAMENTALS
Recursion in C++
Introduction to Recursion:
Definition:
Recursion is a programming technique where a function
calls itself to solve a smaller part of a larger problem.
Real Life Analogy:
Imagine standing between two mirrors – the reflection repeats infinitely. That’s recursion!
Another analogy: Calculating factorial(5):
5! = 5 × 4 × 3 × 2 × 1
Notice how:
5! = 5 × 4!,
4! = 4 × 3!,
and so on…
Recursive Function Call in C++:
Basic Structure:
returnType functionName(parameters) {
if (base_case_condition) {
// Stop calling itself
return some_value;
} else {
// Recursive call
return functionName(smaller_problem);
}
}
Recursive Function Call in C++:
Two Important Parts:
Base Case – The stopping condition (very important, or it loops forever!)
Recursive Case – The function calling itself with smaller input.
Example: Factorial using Recursion
#include<iostream> int main() {
using namespace std; int num = 5;
int factorial(int n) { cout << "Factorial of " << num << " is " <<
factorial(num);
if (n == 0 || n == 1) // Base case
return 0;
return 1;
}
else
Output:
return n * factorial(n - 1); // Recursive
call Factorial of 5 is 120
}
Example: Print Numbers in Reverse using Recursion
int main() {
#include<iostream>
printReverse(5);
using namespace std;
return 0;
void printReverse(int n) {
}
if (n == 0) return; // Base case
Output:
cout << n << " ";
54321
printReverse(n - 1); // Recursive call
}
Example: Sum of Natural Numbers
#include<iostream> int main() {
using namespace std; int num = 5;
int sum(int n) { cout << "Sum = " << sum(num);
if (n == 0) return 0;
return 0; }
else Output:
return n + sum(n - 1); // Recursive call Sum = 15
}
Recursion in C++
Advantages of Recursion Disadvantages of Recursion
Simplifies complex problems Uses more memory (function call
stack)
Cleaner and shorter code for
problems like tree traversal, Slower due to overhead of
factorial, etc. function calls
CLASS ACTIVITY
Problem: Print numbers from 1 to N using
recursion.
#include<iostream> int main() {
if (n == 0) }
return; Output:
}
Problem: Calculate a^b using recursion
(e.g. 2^3 = 8).
#include<iostream> int main() {
int power(int a, int b) { cout << base << "^" << exponent <<
" = " << power(base, exponent);
if (b == 0)
return 0;
return 1;
}
else
Output:
return a * power(a, b - 1);
2^3 = 8
}
Problem: Count how many digits are in a number
using recursion.
void decimalToBinary(int n) { cout << "Binary of " << num << " is ";
if (n == 0) decimalToBinary(num);
return; return 0;
decimalToBinary(n / 2); }
} Binary of 13 is 1101
Problem: Use recursion to print even numbers from 1
to N.
#include<iostream> int main() {
} Output:
return; h
} l
int main() { o