Sum of First N Numbers with Recursion

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to use recursion to find the sum of the first N numbers. We will use the C programming language to write a program that takes an user input, calculates the sum of the first N numbers, and outputs the result to the user. Recursion is a technique used in programming where a function calls itself to solve a problem.

Creating a file and defining the main function

First, we will create a new file named main.c. The main function takes an user input for the value of N, passes this input to the recursive sum function, and then outputs the result.

#include<stdio.h>

int getSum(int);

int main()
{
    printf("This program finds the sum of the first N numbers using recursion.\n");

    int n, sum;
    printf("\nEnter the value of N: ");
    scanf("%d", &n);

    sum = getSum(n);

    printf("\nThe sum of the first %d numbers is %d\n", n, sum);

    return 0;
}

Defining the Recursive Sum Function

In this step, we will define the recursive sum function getSum(). This function takes an integer parameter n, and returns the sum of the first n integers. This function is called recursively until we reach a case where n is less than or equal to 0.

int getSum(int n)
{
    static int sum = 0;

    if (n <= 0) {
        return sum;
    }

    sum += n;
    getSum(n-1);
}

static int sum = 0; statement is used to create a static local variable. Since this is a recursion, the same variable will be used whenever getSum() is called multiple times.

Running the code

The program is now ready to run. Compile and run the program using the following command:

$ gcc main.c -o main
$ ./main

Full Code Listing

#include<stdio.h>

int getSum(int);

int main()
{
    printf("This program finds the sum of the first N numbers using recursion.\n");

    int n, sum;
    printf("\nEnter the value of N: ");
    scanf("%d", &n);

    sum = getSum(n);

    printf("\nThe sum of the first %d numbers is %d\n", n, sum);

    return 0;
}

int getSum(int n)
{
    static int sum = 0;

    if (n <= 0) {
        return sum;
    }

    sum += n;
    getSum(n-1);
}

Summary

In this lab, we learned how to use recursion in C programming to find the sum of the first N numbers. We created a program that takes user input, uses a recursive function to calculate the sum of the first N integers, and outputs the result to the user.

Other C Tutorials you may like