C Program

Write a program using recursion to find the summation of numbers from 1 to n

c program
#include <stdio.h> // Include standard input-output library

// Function prototype declaration
int sum(int m);

void main() {
int n, s;
// Prompt user to enter a number
printf("Enter a number: ");
// Read user input
scanf("%d", &n);
// Call the recursive sum function
s = sum(n);
// Output the result
printf("Sum of numbers from 1 to %d is %d\n", n, s);
}

// Recursive function to calculate the sum of numbers from 1 to m
int sum(int m) {
if (m == 1) // Base case: when m is 1, return 1
return 1;
else
return m + sum(m - 1); // Recursive case: m + sum of numbers from 1 to m-1
}

Explanation

  1. #include <stdio.h>: This line includes the standard input-output library necessary for functions like printf and scanf.

  2. Function Prototype: int sum(int m); declares the sum function before main so that the compiler knows it exists.

  3. main Function:

    • int n, s; declares two integer variables: n (for the user’s input) and s (to store the result of the sum).
    • printf("Enter a number: "); prompts the user to enter a number.
    • scanf("%d", &n); reads an integer input from the user and stores it in n.
    • s = sum(n); calls the sum function, passing the user-provided number n and stores the result in s.
    • printf("Sum of numbers from 1 to %d is %d\n", n, s); outputs the result.
  4. sum Function:

    • This function calculates the sum of numbers from 1 to m using recursion.
    • Base Case: If m is 1, it returns 1, ending the recursion.
    • Recursive Case: Otherwise, it adds m to the result of sum(m - 1), calling itself with m-1.

How Recursion Works Here

If n is 4, the function call sequence would be as follows:

  1. sum(4) = 4 + sum(3)
  2. sum(3) = 3 + sum(2)
  3. sum(2) = 2 + sum(1)
  4. sum(1) = 1 (base case)

Adding these up: 4 + 3 + 2 + 1 = 10, so sum(4) returns 10.

Output Example

If the user enters 4, the output will be:

Enter a number: 4
Sum of numbers from 1 to 4 is 10

Team Educate

About Author

Leave a comment

Your email address will not be published. Required fields are marked *

You may also like

C program to test whether a given identifier is valid or not
C Program

C Program to Test Whether a Given Identifier is Valid or Not

Rules for Valid Identifiers in C: The identifier must begin with a letter or an underscore (_). It cannot start
C program to test whether a given identifier is valid or not
C Program Compiler Design

C program to implement simple code generator

ALGORITHM:1. Start2. Get address code sequence.3. Determine current location of 3 using address (for 1st operand).4. If current location not