Sum 1 to n Recursion
#include <stdio.h> // Standard Input/Output library for printf and scanf
// Function Prototype (Declaration) - Good practice in C
void sum(int n, int s);
// Recursive function to calculate the sum of numbers from 1 to n
// n: the current number to add
// s: the running sum (accumulator)
void sum(int n, int s) {
// Base Case (Stopping Condition): When n becomes 0, the recursion stops.
if (n == 0) {
// Print the final accumulated sum (s)
printf("%d\n", s);
return;
}
// Recursive Step: Call the function again with
// 1. n decreased by 1 (moving to the next number)
// 2. s increased by the current value of n (adding n to the running sum)
sum(n - 1, s + n);
// The 'return;' after the recursive call is optional here since the function returns void.
// It's kept for consistency with the original C++ code structure.
return;
}
int main() {
int n;
// Read the integer n from the user
// The format specifier %d is used for an integer, and &n gives its memory address
scanf("%d", &n);
// Start the recursive process.
// The initial call is sum(n, 0), where n is the limit and 0 is the starting sum.
sum(n, 0);
return 0; // Return 0 to indicate successful execution
}
Comments
Post a Comment