Adding Two Numbers Using Recursion

Beginner

Introduction

In C Programming, we can add two numbers using recursion. Recursion is a function that calls itself repeatedly until the termination condition is met. In this lab, we will create a C program to add two numbers using recursion.

Open main.c File

To begin, open the main.c file in the ~/project/ directory. This is where we will write our C program.

Write the Code

Write the following code in main.c file. The code adds two numbers using recursion.

#include <stdio.h>

// Function to add two numbers using recursion
int add(int m, int n)
{
    if(n == 0)
        return m;

    int y = add(m, n-1) + 1;
    return y;
}

int main()
{
    printf("Adding Two Numbers Using Recursion\n");

    int num1, num2, result;
    printf("Enter first number: ");
    scanf("%d", &num1);

    printf("Enter second number: ");
    scanf("%d", &num2);

    result = add(num1, num2);
    printf("Result is: %d", result);

    return 0;
}

Run the Code

Save the main.c file and compile and run the code. You should be prompted to enter two numbers. After entering the numbers, the program will print the sum of the two numbers.

Understand the Code

The add function takes two integer arguments m and n. If n equals 0, it returns m. If n does not equal 0, it adds 1 to the result of the add function with parameters m and n-1.

The main function prompts the user to enter two integers, calls the add function to add them, and prints the result.

Modify the Code

Try modifying the add function by changing the way it adds the numbers together. For example, instead of adding 1 repeatedly, you could add 2 or 3. Experiment with the code and see what happens.

Summary

In this lab, we learned how to create a C program to add two numbers using recursion. Recursion is a powerful tool for solving problems like this, and it can be a useful technique to have in your programming arsenal.

Other Tutorials you may like