C++ Program to Calculate the Factorial of a Number Using Recursion

Calculating the factorial of a number using recursion in C++ is a common example used to demonstrate the concept of recursion in programming. The factorial of a non-negative integer 𝑛n is denoted by 𝑛!n!, which is the product of all positive integers less than or equal to 𝑛n. The recursive relationship can be defined as:

n! = n × (n−1)!

with the base case being: 0!=10!=1

Here’s a simple C++ program that calculates the factorial of a number using this recursive approach:

#include <iostream>

// Function to calculate factorial recursively

long long factorial(int n) {

    if (n == 0)  // Base case: factorial of 0 is 1

        return 1;

    else

        return n * factorial(n – 1);  // Recursive case

}

int main() {

    int number;

    std::cout << “Enter a positive integer: “;

    std::cin >> number;

    // Check for negative numbers

    if (number < 0) {

        std::cout << “Factorial of a negative number doesn’t exist.” << std::endl;

    } else {

        long long fact = factorial(number);

        std::cout << “Factorial of ” << number << ” is ” << fact << std::endl;

    }

    return 0;

}

Key Points of the Program

  • Function Definition:

The factorial function takes an integer n and returns its factorial. It returns a long long to handle larger results since factorial values grow extremely fast.

  • Recursion:

The function calls itself with n – 1 until it reaches the base case where n equals 0. At that point, it returns 1.

  • Input Handling:

The main function prompts the user to enter a positive integer, reads this input, and then checks if the input is negative. Factorials of negative numbers are not defined, so it provides an appropriate message in that case.

  • Output:

If the input is non-negative, the program calculates the factorial using the recursive function and displays the result.

  • Efficiency and Limitations:

Although recursion is a straightforward way to calculate factorial, it may not be the most efficient method for very large numbers due to potential stack overflow issues with deep recursion. For extremely large numbers, iterative solutions or using languages/libraries that support big integers and tail recursion optimizations might be more suitable.

C++ Program to Calculate the Average of all the Elements Present in an Array

Creating a C++ program to calculate the average of all elements in an array involves initializing an array, computing the sum of its elements, and then dividing the sum by the number of elements to obtain the average. This is a fundamental concept that is frequently utilized in data analysis and statistics within programming.

Here’s a C++ program that demonstrates how to calculate the average of all the elements in an array:

#include <iostream>

int main() {

    // Define the array

    int arr[] = {10, 20, 30, 40, 50};

    int n = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

    // Initialize sum

    int sum = 0;

    // Calculate the sum of all elements in the array

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

        sum += arr[i];

    }

Here’s how the program works:

  • The array arr is defined with some example values.
  • The size of the array is calculated using sizeof(arr) / sizeof(arr[0]).
  • The program initializes a variable sum to 0.
  • The for loop iterates through the array, adding each element’s value to sum.
  • After the loop completes, the average is calculated by dividing sum by the number of elements (n).
  • The program outputs the average of all the elements in the array.

C++ Program for Array Rotation

Array Rotation involves shifting all elements in an array either to the left or to the right by a certain number of positions. In C++, you can implement array rotation efficiently using various approaches such as reversing segments of the array or using a temporary array.

Example program that demonstrates how to rotate an array to the left by a specified number of positions using a temporary array:

#include <iostream>

void rotateArray(int arr[], int size, int positions) {

    // Make sure positions is within the array’s length

    positions = positions % size;

    // Temporary array to hold the elements

    int temp[positions];

    // Copy the first ‘positions’ elements to the temporary array

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

        temp[i] = arr[i];

    }

    // Shift the remaining elements to the left

    for (int i = 0; i < size – positions; i++) {

        arr[i] = arr[i + positions];

    }

    // Copy the elements from the temporary array back to the original array

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

        arr[size – positions + i] = temp[i];

    }

}

int main() {

    // Define the array

    int arr[] = {1, 2, 3, 4, 5, 6, 7};

    int size = sizeof(arr) / sizeof(arr[0]);

    // Number of positions to rotate the array to the left

    int positions = 2;

    // Rotate the array

    rotateArray(arr, size, positions);

    // Output the rotated array

    std::cout << “Array after rotating left by ” << positions << ” positions: “;

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

        std::cout << arr[i] << ” “;

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the program works:

  • The function rotateArray takes an array, its size, and the number of positions to rotate as parameters.
  • It uses the modulo operator (%) to ensure the positions parameter is within the bounds of the array’s length.
  • A temporary array is used to hold the first positions elements from the original array.
  • The function shifts the remaining elements in the original array to the left by positions positions.
  • The elements in the temporary array are then copied back to the end of the original array.
  • In the main function, the program prints the array after rotating it to the left by the specified number of positions.

C++ Program to Calculate Power Using Recursion

Calculating the Power of a number using recursion involves repeatedly multiplying a base by itself a certain number of times. In C++, you can implement this by defining a recursive function that multiplies the base number until the exponent decreases to zero, which serves as the base case.

Below is a C++ program that calculates the power of a base number raised to an exponent using recursion. This program demonstrates not only the direct recursive approach but also handles negative exponents, which require a little bit of additional logic.

#include <iostream>

// Recursive function to calculate power of a number

double power(double base, int exponent) {

    if (exponent == 0) {

        // Any number raised to the power of 0 is 1

        return 1;

    } else if (exponent < 0) {

        // Handle negative exponent

        return 1 / power(base, -exponent);

    } else {

        // Recursive case: base * power(base, exponent – 1)

        return base * power(base, exponent – 1);

    }

}

int main() {

    double base;

    int exponent;

    std::cout << “Enter base: “;

    std::cin >> base;

    std::cout << “Enter exponent: “;

    std::cin >> exponent;

    double result = power(base, exponent);

    std::cout << base << ” raised to the power of ” << exponent << ” is ” << result << std::endl;

    return 0;

}

Explanation:

  • Function Definition:

The power function takes two parameters, base (of type double to handle fractional numbers) and exponent (of type int).

  • Base Case:

If exponent == 0, the function returns 1, because any number raised to the power of 0 is 1.

  • Handling Negative Exponents:

If the exponent is negative, the function returns the reciprocal of the base raised to the absolute value of the exponent. This is accomplished by 1 / power(base, -exponent).

  • Recursive Case:

If the exponent is positive, the function returns base * power(base, exponent – 1). This expression multiplies the base by the result of the power function called with the exponent decreased by 1, recursively breaking down the problem until it reaches the base case.

  • Input/Output:

The main function handles user input and output, prompting the user to enter the base and exponent, and then it prints the result.

Performance Note

While recursion provides a clear and concise solution for calculating powers, it’s not the most efficient in terms of performance, especially for large exponents. An iterative approach or using the method of exponentiation by squaring (which can also be implemented recursively) would be more efficient, especially for larger numbers, as it reduces the time complexity significantly.

C++ Program for Variadic Function Templates

Variadic Function templates in C++ allow you to write flexible functions that can accept any number of arguments, regardless of their types. This is particularly useful for creating functions like custom print functions, aggregators, or any function that needs to handle a list of varying types of arguments. Variadic templates utilize a special syntax with ellipsis (…) to handle an arbitrary number of template arguments.

Below is a simple C++ program demonstrating the use of variadic function templates. We’ll write two examples:

1. A print function that can accept and print any number of arguments.

2. A sum function that can add up any number of integer arguments.

Example 1: Print Function

This function will print each argument followed by a space.

#include <iostream>

// Base function needed to end the recursion

void print() {

std::cout << std::endl; // End the line at the end of output

}

// Template variadic function to print any number of arguments

template<typename T, typename… Args>

void print(const T& firstArg, const Args&… args) {

std::cout << firstArg << ” “; // Print the first argument

print(args…); // Recursive call with the rest of the arguments

}

int main() {

print(1, 2.5, “hello”, ‘a’);

return 0;

}

 

Example 2: Sum Function

This function will add up any number of integer arguments. This demonstrates using recursion in variadic templates to compute a result.

#include <iostream>

// Base function to end the recursion and return the last element

int sum() {

return 0; // Return 0 when there are no elements left

}

// Template variadic function to sum any number of integers

template<typename… Args>

int sum(int firstArg, Args… args) {

return firstArg + sum(args…); // Recursive call to sum the rest of the arguments

}

int main() {

std::cout << “Sum of 1, 2, 3, 4 is ” << sum(1, 2, 3, 4) << std::endl;

return 0;

}

 

How Variadic Templates Work

  1. Print Function

The print function is a template that takes a first argument of any type and then uses a parameter pack (Args…) for the rest of the arguments.

  • It prints the first argument, then recursively calls itself with the remainder of the arguments (args…).
  • The recursion ends when it hits the base print() function that just prints a newline.

2. Sum Function

Similar to print, the sum function uses a template to handle an initial integer and a parameter pack for the rest.

  • It recursively sums each integer by adding the first argument to the result of a recursive call.
  • The base case here is a sum() function that returns 0, which handles the scenario when the parameter pack is empty.

C++ Program to Print Reverse Floyd Pattern Triangle Pyramid

To create a C++ program that prints a reverse Floyd’s Triangle, we need to reverse the pattern seen in the traditional Floyd’s Triangle. In this pattern, numbers will decrease with each row rather than increasing. The highest number starts at the top and decreases as we proceed downwards, maintaining the staggered layout of Floyd’s Triangle.

C++ Code for Reverse Floyd’s Triangle:

#include <iostream>

using namespace std;

int main() {

    int rows;

    // Ask the user for the number of rows

    cout << “Enter the number of rows for the Reverse Floyd’s Triangle: “;

    cin >> rows;

    // Determine the starting number

    int start_number = rows * (rows + 1) / 2;  // Sum of first ‘rows’ natural numbers

    cout << “Reverse Floyd’s Triangle:” << endl;

    // Outer loop for handling the number of rows

    for (int i = rows; i > 0; i–) {

        // Inner loop for handling the number of columns in each row

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

            cout << start_number << ” “;

            start_number–;  // Decrement number for next place

        }

        cout << endl; // Move to the next line after each row

    }

    return 0;

}

Explanation:

  1. Variable Declaration and Input:

    • rows: The user specifies how many rows the triangle should have.
    • start_number: Calculated as the sum of the first rows natural numbers using the formula 𝑛(𝑛+1)22n(n+1)​. This gives the starting point for the highest number in the triangle.
  2. Printing the Triangle:

    • Outer Loop: Runs backward from rows to 1. Each iteration corresponds to a row in the triangle.
    • Inner Loop: Handles the number of entries in each row, which matches the current row number (i). It prints out the current start_number and decrements it after each print.
  3. Output:

Each row decreases in length sequentially, and numbers decrease from the top down.

Example Output:

If the user inputs 4 for the number of rows, the output will be:

Reverse Floyd’s Triangle:

10

9 8

7 6 5

4 3 2 1

C++ Program to Print Floyd’s pattern Triangle Pyramid

Floyd’s Triangle is a well-known pattern in the world of programming and mathematics. It is a triangular array of natural numbers, arranged in a staggered format where the rows increase in length incrementally. Each row contains consecutive numbers starting from 1.

In this C++ program, we will generate Floyd’s Triangle based on the number of rows specified by the user. The pattern involves filling the rows with increasing numbers, starting with 1 at the top.

C++ Code to Print Floyd’s Triangle:

#include <iostream>

using namespace std;

int main() {

    int rows, number = 1;

    // Prompting user to enter the number of rows

    cout << “Enter the number of rows for Floyd’s Triangle: “;

    cin >> rows;

    cout << “Floyd’s Triangle:” << endl;

    // Outer loop for handling the number of rows

    for (int i = 1; i <= rows; i++) {

        // Inner loop for handling the number of columns in each row

        for (int j = 1; j <= i; j++) {

            cout << number << ” “;

            number++;  // Increment number for next place

        }

        cout << endl; // Move to the next line after each row

    }

    return 0;

}

Explanation:

  1. Variables Declaration:

The variable rows stores the number of rows, and number keeps track of the current number to be printed, starting at 1.

  1. Input from User:

The user is asked to specify the number of rows they wish to generate in Floyd’s Triangle.

  1. Generating Floyd’s Triangle:

    • Outer Loop (i): Runs from 1 to rows, where i represents the current row number.
    • Inner Loop (j): Runs from 1 to i, reflecting that the number of elements in each row increases with the row number. Within this loop, the number is printed and then incremented.
    • Each row is printed on a new line (cout << endl).
  2. Output:

The triangle displays numbers in a staggered format, increasing with each row.

Example Output:

If the user enters 5 for the number of rows, the output will look like this:

Floyd’s Triangle:

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

This program clearly illustrates how nested loops can be used to manage and output data in specific formats, making it a good example for beginners learning about loops and sequence generation in C++.

C++ Program to Print Pascal’s Triangle

Printing Pascal’s Triangle in C++ is a useful exercise to practice nested loops and understand combinatorial mathematics. Pascal’s Triangle is a triangular array where each entry is the sum of the two directly above it on the previous row. The outer edges of the triangle are populated with ones, and each number inside the triangle is the sum of the two numbers above it.

Here, we’ll write a C++ program that prompts the user to enter the number of rows they want in Pascal’s Triangle, and then outputs the triangle.

C++ Code:

#include <iostream>

using namespace std;

// Function to calculate factorial

int factorial(int n) {

    int fact = 1;

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

        fact *= i;

    }

    return fact;

}

// Function to calculate binomial coefficient (n choose k)

int binomialCoefficient(int n, int k) {

    return factorial(n) / (factorial(k) * factorial(n – k));

}

// Function to print Pascal’s Triangle

void printPascalsTriangle(int rows) {

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

        // Printing leading spaces

        for (int space = 1; space <= rows – n; space++) {

            cout << ” “;

        }

        // Calculating and printing the values in each row

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

            cout << binomialCoefficient(n, k) << ” “;

        }

        cout << endl;

    }

}

int main() {

    int rows;

    // Asking the user for the number of rows

    cout << “Enter the number of rows for Pascal’s Triangle: “;

    cin >> rows;

    // Printing Pascal’s Triangle

    printPascalsTriangle(rows);

    return 0;

}

Explanation:

  1. Factorial Function:

This function computes the factorial of a given number, used in the calculation of the binomial coefficients.

  1. Binomial Coefficient Function:

Computes the binomial coefficient using the factorial function. The binomial coefficient (𝑛𝑘)(kn​) is crucial for determining the values in Pascal’s Triangle.

  1. Printing Pascal’s Triangle:

    • Outer Loop: Iterates over each row of the triangle.
    • First Inner Loop: Prints spaces to align the numbers properly, creating the triangular shape.
    • Second Inner Loop: Computes and prints each number in the row using the binomial coefficient function.
  2. Main Function:

Takes the number of rows from the user and calls the function to print Pascal’s Triangle.

Program Output:

If the user enters 5 for the number of rows, the output will be:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

This triangle visually represents the binomial coefficients, and the values correspond to combinations. Each number represents the number of ways to choose a subset of elements from a larger set where order does not matter. This program provides a foundational understanding of how loops and mathematical functions can be utilized to solve combinatorial problems in C++.

C++ Program to Print Hollow Star Pyramid in a Diamond Shape

Creating a hollow star pyramid in a diamond shape is an interesting exercise to practice nested loops and conditional statements in C++. This pattern involves printing a hollow diamond made of stars (*), where the diamond consists of two parts: the upper pyramid and the inverted lower pyramid, both hollow except for their borders.

Example: Hollow Star Pyramid in a Diamond Shape

This program will prompt the user to enter the number of rows for the upper part of the diamond. The lower part will automatically be generated to match the upper part, creating a symmetrical diamond shape.

C++ Code:

#include <iostream>

using namespace std;

int main() {

    int rows;

    // User inputs the number of rows for the upper part of the diamond

    cout << “Enter the number of rows: “;

    cin >> rows;

    // Print the upper part of the diamond

    for (int i = 1; i <= rows; ++i) {

        // Print leading spaces

        for (int j = 1; j <= rows – i; ++j) {

            cout << ” “;

        }

        // Print stars and hollow spaces

        for (int j = 1; j <= 2 * i – 1; ++j) {

            if (j == 1 || j == 2 * i – 1) {

                cout << “*”;

            } else {

                cout << ” “;

            }

        }

        cout << endl;

    }

    // Print the lower part of the diamond

    for (int i = rows – 1; i > 0; –i) {

        // Print leading spaces

        for (int j = 1; j <= rows – i; ++j) {

            cout << ” “;

        }

        // Print stars and hollow spaces

        for (int j = 1; j <= 2 * i – 1; ++j) {

            if (j == 1 || j == 2 * i – 1) {

                cout << “*”;

            } else {

                cout << ” “;

            }

        }

        cout << endl;

    }

    return 0;

}

Explanation:

  1. Header and Namespace: Includes <iostream> for input and output operations and uses the std
  2. Input: The user specifies the number of rows for the upper half of the diamond.
  3. Upper Diamond:
    • Outer Loop: Manages the rows of the upper pyramid.
    • First Inner Loop: Controls the spaces before the stars begin, decreasing as the rows increase.
    • Second Inner Loop: Handles the printing of stars and hollow spaces. Stars are printed only at the edges (j == 1 or j == 2 * i – 1), leaving the rest as spaces.
  4. Lower Diamond:
    • Outer Loop: Manages the rows of the inverted lower pyramid.
    • First Inner Loop: Similar to the upper part but for spacing, it increases as you move deeper into the lower part.
    • Second Inner Loop: Similar to the upper part in terms of star placement and hollow spaces.

Program Output:

If the user inputs 4 for the number of rows, the output will be:

*

* *

*   *

*     *

*   *

* *

*

This pattern creates a visually appealing hollow diamond using nested loops and conditional checks to determine where to print stars and spaces, illustrating how to manipulate console output effectively in C++.

C++ Program to Print Inverted Hollow Star Pyramid Pattern

Creating an inverted hollow star pyramid pattern in C++ is an excellent exercise to deepen your understanding of loops and conditional statements. This pattern features an inverted pyramid where only the border of the pyramid is marked with stars (*), leaving the inside hollow or empty.

Example: Inverted Hollow Star Pyramid Pattern

This program will display an inverted hollow star pyramid based on the number of rows specified by the user. The top row will be completely filled with stars, and subsequent rows will only have stars at the borders, with the inner part being hollow until the last row which has just one star.

C++ Code:

#include <iostream>

using namespace std;

int main() {

    int rows;

    // User inputs the number of rows for the pyramid

    cout << “Enter the number of rows: “;

    cin >> rows;

    // Print the inverted hollow pyramid

    for (int i = rows; i > 0; –i) {

        // Print leading spaces

        for (int j = 0; j < rows – i; ++j) {

            cout << ” “;

        }

        // Print stars and hollow spaces

        for (int j = 1; j <= 2 * i – 1; ++j) {

            if (j == 1 || j == 2 * i – 1 || i == rows) {

                cout << “*”; // Print star at borders and top row

            } else {

                cout << ” “; // Print space inside the pyramid

            }

        }

        cout << endl;

    }

    return 0;

}

Explanation:

  1. Header and Namespace: The program includes <iostream> for input/output operations and uses the std
  2. Input: The user is prompted to enter the number of rows for the pyramid. This number determines the height of the inverted pyramid.
  3. Loop for Rows:
    • Outer Loop: Runs from the specified number of rows down to 1, handling each row of the pyramid.
    • First Inner Loop: Manages the spaces before the stars begin on each row. These spaces increase as you move to lower rows (which are visually higher in the inverted pyramid).
    • Second Inner Loop: Manages the printing of stars and hollow spaces. Stars are printed at the first and last positions (j == 1 or j == 2 * i – 1) and across the entire top row (i == rows). The rest is filled with spaces.

Program Output:

Assuming the user inputs 5 for the number of rows, the output will be:

*********

*     *

*   *

* *

*

This program uses a combination of loops and conditional logic to create an appealing pattern. Such exercises are useful for practicing how to manipulate output based on the location within the loops, a key skill in developing more complex algorithms and applications in C++.

error: Content is protected !!