C++ RECURSION
NAME: MUZZAMIL EJAZ
ROLL NO: 23-SCET-CS-007
SUBMITTED TO: MS SAMRA
DEPARTMENT: BSCS
PROGRAMMING FUNDAMENTALS
....
}
INTRODUCTION TO C++ RECURSION
• Definition:
• "Recursion involves a function calling itself during execution."
• Purpose:
• "Used to solve problems by breaking them into smaller, identical subproblems.“
• Syntax:
return type recursive function {
....
// Base Condition
// Recursive Case
....
}
INTRODUCTION TO C++ RECURSION
• Key Concept:
• "Recursive functions comprise a base case and a recursive case.“
• “The recursion continues until some condition is met.”
• “To prevent infinite recursion, if…else statement can be used
where one branch makes the recursive call and other does not.”
ADVANTAGES OF C++ RECURSION
• Clarity and Elegance:
• "Recursion often leads to clear and elegant solutions, especially for problems with inherent
recursive structures."
• Simplified Code:
• "Certain problems are naturally expressed using recursive logic, resulting in more concise and
readable code."
• Modularity:
• "Recursive functions allow for modular design, where each function handles a specific part of
the problem."
DISADVANTAGES AND CONSIDERATIONS
• Stack Overflow Risk:
• "Deep recursion can lead to stack overflow due to the accumulation of function call frames on
the stack."
• Overhead:
• "Recursion can have slightly higher overhead compared to iterative solutions due to the function
call stack."
• Understanding Required:
• "Understanding the problem thoroughly is crucial to avoid designing inefficient or incorrect
recursive solutions."
• Example:
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
}