1. Introduction
Recursion is a powerful concept in programming where a function calls itself to solve a problem. One of the classic problems solved using recursion is finding the sum of the first 'n' natural numbers. This post will guide you through writing a C program to achieve this using recursion.
2. Program Overview
The C program will:
1. Prompt the user to input a number 'n'.
2. Calculate the sum of the first 'n' natural numbers using recursion.
3. Display the result.
3. Code Program
#include <stdio.h>
// Recursive function to find the sum of the first n natural numbers
int sumOfNaturalNumbers(int n) {
if(n == 0)
return 0; // Base condition
else
return n + sumOfNaturalNumbers(n - 1); // Recursive call
}
int main() {
int num;
// Taking input from the user
printf("Enter a positive integer: ");
scanf("%d", &num);
// Ensuring that the number entered is non-negative
if(num < 0) {
printf("Please enter a non-negative integer.");
return 1;
}
// Displaying the result
printf("Sum of the first %d natural numbers is: %d", num, sumOfNaturalNumbers(num));
return 0;
}
Output:
Enter a positive integer: 5 Sum of the first 5 natural numbers is: 15
4. Step By Step Explanation
1. Recursive Function:
- The function sumOfNaturalNumbers is defined to calculate the sum recursively.
- It takes an integer 'n' as its argument.
- If n is 0, it returns 0 (base case).
- Otherwise, it returns the sum of 'n' and the sum of the first 'n-1' natural numbers. This is achieved by the function calling itself.
2. User Input:
- The user is prompted to input a positive integer.
- A check is performed to ensure the number entered is non-negative.
3. Displaying Result:
- The result, i.e., the sum of the first 'n' natural numbers, is displayed using the printf function.
By using recursion, we have efficiently solved the problem in a logical and concise manner. This example demonstrates the elegance and power of recursive techniques in programming.
Comments
Post a Comment
Leave Comment