0% found this document useful (0 votes)
2 views10 pages

Lab 8 Ds

Uploaded by

wondimuredwan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Lab 8 Ds

Uploaded by

wondimuredwan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Lab

Simple Example of Recursion

#include <iostream>

using namespace std;

// Function to calculate factorial using recursion

int factorial(int n) {

if (n == 0) { // Base case

return 1;

else { // Recursive case

return n * factorial(n - 1);

int main() {

int number;

cout << "Enter a number: ";

cin >> number;

// Calculating factorial

int result = factorial(number);

cout << "Factorial of " << number << " is " << result << endl;
return 0;

Example of Tail Recursion

#include <iostream>

using namespace std;

// Tail-recursive helper function

int factorialHelper(int n, int accumulator) {

if (n == 0) return accumulator; // Base case

return factorialHelper(n - 1, n * accumulator); // Tail call

// Main factorial function

int factorial(int n) {

return factorialHelper(n, 1); // Start with accumulator = 1

int main() {

int number;

cout << "Enter a number: ";

cin >> number;


cout << "Factorial of " << number << " is " << factorial(number) << endl;

return 0;

Example of Indirect Recursion

#include <iostream>

using namespace std;

// Function to check if a number is even

bool isEven(int n);

// Function to check if a number is odd

bool isOdd(int n) {

if (n == 0) return false; // Base case

return isEven(n - 1); // Indirect recursive call

// Function to check if a number is even

bool isEven(int n) {

if (n == 0) return true; // Base case

return isOdd(n - 1); // Indirect recursive call


}

int main() {

int number;

cout << "Enter a number: ";

cin >> number;

if (isEven(number))

cout << number << " is Even." << endl;

else

cout << number << " is Odd." << endl;

return 0;

Example: Nested Recursive Function

Let’s consider the following mathematical function f(n):

f(n) = f( f (n−1)) if n>0

f(n)=1 if n=0

Example
#include <iostream>

using namespace std;


// Nested recursive function

int nestedRecursion(int n) {

if (n >= 0) return 1; // Base case, try with condition n<=0, it may crashed

return nestedRecursion(nestedRecursion(n - 1)); // Nested recursive call

int main() {

int number;

cout << "Enter a number: ";

cin >> number;

cout << "Result: " << nestedRecursion(number) << endl;

return 0;

Example to check it do not go to depth and get crashed.


#include <iostream>

using namespace std;

// Controlled nested recursion with recursion depth limit

int nestedRecursion(int n, int depth = 0) {

if (depth > 100) { // Stop if the recursion depth exceeds 100


cout << "Recursion depth exceeded." << endl;

return -1; // Return -1 to indicate overflow

if (n <= 0) return 1; // Base case

return nestedRecursion(nestedRecursion(n - 1, depth + 1), depth + 1);

int main() {

int number;

cout << "Enter a number: ";

cin >> number;

int result = nestedRecursion(number);

if (result != -1) {

cout << "Result: " << result << endl;

} else {

cout << "Error: Recursion limit reached!" << endl;

return 0;

}
Backtracking Example: The N-Queens Problem

The N-Queens problem is a classic example where backtracking is used. The goal
is to place N queens on an NxN chessboard such that no two queens threaten each
other. This means:

1. No two queens can be on the same row.


2. No two queens can be on the same column.
3. No two queens can be on the same diagonal.

Approach

1. Place a queen in the first row, then try to place another queen in the next
row.
2. For each row, place a queen in every column one by one and check whether
the current placement is valid (i.e., it doesn’t result in any queens attacking
each other).
3. If placing a queen in a particular column is not valid, backtrack and move
the queen to the next column.
4. Repeat the process for all rows until a solution is found or all possibilities
are exhausted.

Example: Solving N-Queens Using Backtracking


#include <iostream>

#include <vector>

using namespace std;

bool isSafe(const vector<vector<int> >& board, int row, int col, int n) {

// Check the column

for (int i = 0; i < row; i++) {

if (board[i][col] == 1) {

return false;

}
}

// Check the upper left diagonal

for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {

if (board[i][j] == 1) {

return false;

// Check the upper right diagonal

for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {

if (board[i][j] == 1) {

return false;

return true;

bool solveNQueens(vector<vector<int> >& board, int row, int n) {

if (row == n) {

// All queens are placed successfully

return true;
}

for (int col = 0; col < n; col++) {

if (isSafe(board, row, col, n)) {

board[row][col] = 1; // Place the queen

// Recursively place queens in the next row

if (solveNQueens(board, row + 1, n)) {

return true;

// Backtrack: Remove the queen if placing it leads to a solution

board[row][col] = 0;

return false; // No valid placement found, backtrack

void printBoard(const vector<vector<int> >& board, int n) {

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

cout << (board[i][j] ? "Q " : ". ");


}

cout << endl;

int main() {

int n;

cout << "Enter the value of n: ";

cin >> n;

vector<vector<int> > board(n, vector<int>(n, 0));

if (solveNQueens(board, 0, n)) {

cout << "Solution found: \n";

printBoard(board, n);

} else {

cout << "No solution exists!" << endl;

return 0;

You might also like