Write a function that calculates the sum of a range of integers using recursion.


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>

int sum(int lowerLimit, int upperLimit)
{
	if (lowerLimit > upperLimit)
		return 0;
	/* OR
		if (lowerLimit == upperLimit)
			return lowerLimit;
	
	*/
	return lowerLimit + sum(lowerLimit + 1, upperLimit);
}

void main()
{
	int lowerLimit, upperLimit;

	printf("Enter the lower limit: ");
	scanf("%d", &lowerLimit);
	printf("Enter the upper limit: ");
	scanf("%d", &upperLimit);

	printf("Sum of integers from %d to %d are the following = %d ", lowerLimit, upperLimit, sum(lowerLimit, upperLimit));

	getch();
}


Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Asymptotic Analysis 21