Introduction to Recursion
Recursion When a function calls itself , until a specific condition is met.
The function void f() print(1) and execute f(), but f() calls the same function void f() again,
hence a stack memory is created a f(), at line 2 which is in waiting.
This continues till the whole stack memory is utilized.
This results in Segmentation fault known as Stack overflow.
The termination condition in the recursion function is known as Base Case., here in
above example base case is: if (count==3) return;
The Stack space stores the non-executed or waiting functions.
Recursion Tree is diagrammatic representation of the recursion function.
Q. Problem statement
You are given an integer ‘n’. Your task is to return an array containing integers from 1 to ‘n’
(in increasing order) without using loops.
#include <vector>
vector<int> printNosHelper(int n, vector<int>& result) {
if (n == 1) {
result.push_back(n);
return result;
printNosHelper(n - 1, result);
result.push_back(n);
return result;
vector<int> printNos(int n) {
vector<int> result;
return printNosHelper(n, result);
Q. Problem statement
You are given an integer ‘n’. Print “Coding Ninjas” ‘n’ times, without using a loop.
Example: Input: ‘n’ = 4
Output: Coding Ninjas Coding Ninjas Coding Ninjas Coding Ninjas
void printNTimesHelper( int n, std::vector<std::string>& result){
if (n == 0) {
return;
printNTimesHelper(n-1 , result);
result.push_back("Coding Ninjas");
std::vector<std::string> printNTimes(int n) {
std::vector<std::string> result;
printNTimesHelper(n,result);
return result;
Q. Problem statement
You are given an integer ‘n’. The task is to return an array containing integers from ‘n’ to ‘1’
(in decreasing order) without using loops.
void print(int start,int n,vector<int> &v){
if(n<start) return;
v.push_back(n);
print(start,n-1,v);
vector<int> printNos(int x) {
vector<int>ans;
print(1,x,ans);
return ans;
Q. Problem statement
You are given an integer ‘n’. Your task is determining the sum of the first ‘n’ natural
numbers and returning it.
int firstN(int i, int sum) {
if (i < 1) {
return sum;
return firstN(i-1, sum+i);
long long sumFirstN(long long n) {
return firstN(n, 0);