#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
#include <stdio.h>
: This line includes the standard input-output library necessary for functions likeprintf
andscanf
.Function Prototype:
int sum(int m);
declares thesum
function beforemain
so that the compiler knows it exists.main
Function:int n, s;
declares two integer variables:n
(for the user’s input) ands
(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 inn
.s = sum(n);
calls thesum
function, passing the user-provided numbern
and stores the result ins
.printf("Sum of numbers from 1 to %d is %d\n", n, s);
outputs the result.
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 ofsum(m - 1)
, calling itself withm-1
.
- This function calculates the sum of numbers from 1 to
How Recursion Works Here
If n
is 4, the function call sequence would be as follows:
sum(4)
= 4 +sum(3)
sum(3)
= 3 +sum(2)
sum(2)
= 2 +sum(1)
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