This blog is under construction

Sunday, 21 July 2013

C program to find the sum of first n natural numbers using recursion

Write a C program to find the sum of first N natural numbers using recursion.


  #include <stdio.h>

  /* find the sum of first n natural numbers */
  void findSum(int num, int *res) {
        if (num) {
                *res = *res + num;

                /* recursive call */
                findSum(num - 1, res);
        }
        return;
  }

  int main() {
        int input, sum = 0;

        /* get the input value from the user */
        printf("Enter your input value:");
        scanf("%d", &input);

        /* find the sum of first n natural numbers */
        findSum(input, &sum);

        /* print the result */
        printf("Sum of first %d natural numbers is %d\n", input, sum);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:10
  Sum of first 10 natural numbers is 55


No comments:

Post a Comment