C Program Sum of One to N by Recursion

By | March 9, 2020

C Program Sum of One to N by Recursion

/*C Program To Add all natural numbers 1 to N
Using Recursion
*/

#include <stdio.h>

/* Function prototype */
int sumNumbers(int n);

/* main function */

int main() {
    int num;
    printf("Enter a positive integer\nto add all numbers upto: ");
    scanf("%d", &num);
    printf("Sum of Numbers Upto %d = %d", num, sumNumbers(num));
    return 0;
}

int sumNumbers(int n) {
    
	if (n == 0)
	    return 0;
    else
        return n + sumNumbers(n - 1);
    
}

Output

Enter a positive integer
to add all numbers upto: 5
Sum of Numbers Upto 5 = 15

Loading

Leave a Reply

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