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. }

Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]

Join Our Facebook Group

Share this example

Download Android App

download android app

Popular C Examples


Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube