C Program to Print Sum of First N Numbers Using Recursion


Recursion in C means a function calling itself. The function dspsum recursively adds the number to the variable sum by decreasing the value of num in every call till it becomes 0.

  1. //C program to print sum of first n numbers using recursion
  2. #include <stdio.h>
  3. void dspsum(int);
  4. int main()
  5. {
  6. int num;
  7. printf("Enter the Nth number: ");
  8. scanf("%d", &num); //taking input from user
  9. dspsum(num); //calling the recursive function
  10. return 0;
  11. }
  12. void dspsum(int num)
  13. {
  14. static int sum = 0;
  15. if (num == 0)
  16. {
  17. printf("Sum of first N numbers is %d\n", sum);
  18. return;
  19. }
  20. else
  21. {
  22. sum += num;
  23. dspsum(--num);
  24. }

Output

Output!