SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
Given a range "N", print the sum of natural numbers till N
Write a function that receives an integer "N", and determines the sum of natural numbers till N.
Implementation:
#include
/* Recursive Function to Add natural numbers. Until the number becomes 0, add the number & call the function passing number - 1 */ int sum(int no) { /* Fails when Input number becomes 0 */ if(no!=0) /* Recursively add (No + (No-1)) & Return the sum*/ return no+add(no-1); } /* Driver function to test the above function */ int main() { /* Input Number, a positive integer */ int no; /* Prompt for the user to enter an integer */ printf("Enter an integer:"); /* Store the user entered number in "no" */ scanf("%d",&no); /* Print the sum of natural numbers, return value of the function "sum" */ printf("Sum= %d",sum(no)); /* Returns 0 since, main function doesn't return any value */ return 0; }
Output:
Enter an integer: 10
Sum=55
PREVIOUS
NEXT
HOME