w3resource logo


C Programming Exercises

C Exercises: Calculate the sum of numbers from 1 to n

Secondary Nav

C Recursion : Exercise-2 with Solution

Write a program in C to calculate the sum of numbers from 1 to n using recursion.
Test Data :
Input the last number of the range starting from 1 : 5
Expected Output :

The sum of numbers from 1 to 5 : 
15

C Code:

#include<stdio.h>
 
int sumOfRange(int);
 
int main() 
{
   int i, n1;
   int sum;
	printf("\n\n Recursion : calculate the sum of numbers from 1 to n :\n");
	printf("-----------------------------------------------------------\n");    
 
   printf(" Input the last number of the range starting from 1 : ");
   scanf("%d", &n1);
 
   sum = sumOfRange(n1); 
   printf("\n The sum of numbers from 1 to %d : %d\n\n", n1, sum);
 
   return (0);
}
 
int sumOfRange(int n1) 
{
   int res;
   if (n1 == 1) 
   {
      return (1);
   } else 
   {
      res = n1 + sumOfRange(n1 - 1); //calling the function sumOfRange itself
   }
   return (res);
}

Flowchart :

Flowchart: Calculate the sum of numbers 1 to n.

C Practice online:

#include<stdio.h>
 
int sumOfRange(int);
 
int main() 
{
   int i, n1;
   int sum;
	printf("\n\n Recursion : calculate the sum of numbers from 1 to n :\n");
	printf("-----------------------------------------------------------\n");    
 
   printf(" Input the last number of the range starting from 1 : ");
   scanf("%d", &n1);
 
   sum = sumOfRange(n1); 
   printf("\n The sum of numbers from 1 to %d : %d\n\n", n1, sum);
 
   return (0);
}
 
int sumOfRange(int n1) 
{
   int res;
   if (n1 == 1) 
   {
      return (1);
   } else 
   {
      res = n1 + sumOfRange(n1 - 1); //calling the function sumOfRange itself
   }
   return (res);
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program