Function part 7 (Recursion 2)

Estimated reading: 4 minutes 161 Views

Example 1:

#include <iostream>
using namespace std;
int sum(int n)
{
    if (n == 1)
        return 1;
    else
        return n + sum(n - 1);
}

int main()
{
    cout << sum(5) << endl;
    return 0;
}

This function calculates the sum of the first n natural numbers. The first n natural numbers are the numbers from 1 to n.

The function works by recursively calling itself to calculate the sum of the first n - 1 natural numbers. If the input number n is 1, the function simply returns the number 1, because the sum of the first natural number is 1. Otherwise, the function returns the sum of the input number n and the sum of the first n - 1 natural numbers.

Output:

15

Example 2:

#include <iostream>
using namespace std;
int sum(int x, int y)
{
    if (x == y)
        return x;
    else
        return y + sum(x, y - 1);
}

int main()
{
    cout << sum(4, 6) << endl;
    return 0;
}

This is a recursive function sum. It takes two integer parameters, x and y, which represent the range of numbers to sum. Here’s how the function works:

  • The base case: If x is equal to y, it means we have reached the end of the range, so it returns x. This is the terminating condition for the recursion.
  • The recursive case: If x is not equal to y, it adds the current value of y to the result of calling the sum function again with the same x and y-1. This effectively breaks down the sum of the range into smaller subproblems by reducing the upper bound (y) by 1 in each recursive call.

In the main function, it calls the sum function with the arguments 4 and 6 and then outputs the result to the console using cout. In this case, it will calculate the sum of integers from 4 to 6 (inclusive) and print the result.

When you run this code, it will output the sum of integers from 4 to 6, which is 4 + 5 + 6 = 15. So, the output of this code will be:

15
Share this

Function part 7 (Recursion 2)

Or copy link

CONTENTS
English