Program to Find the Sum of Numbers in a Given Range in C++
Sum of Numbers in a Given Range
Given two integer inputs num1 and num2, the objective is to find the sum of all numbers in the given range using C++ programming.
We will explore different methods to achieve this.
Method 1: Using a for Loop
We iterate from num1 to num2, adding each number to a sum variable.
#include <iostream>
using namespace std;
int main() {
int num1, num2, sum = 0;
cout << "Enter the range (num1 num2): ";
cin >> num1 >> num2;
for (int i = num1; i <= num2; i++) {
sum += i;
}
cout << "Sum of numbers in given range: " << sum;
return 0;
}
Output:
Enter the range (num1 num2): 2 4 Sum of numbers in given range: 9
Method 2: Using the Formula
We use the formula for the sum of the first n natural numbers: sum = n(n+1)/2. Using this, we derive:
sum = (num2 * (num2 + 1) / 2) - ((num1 - 1) * num1 / 2)
#include <iostream>
using namespace std;
int main() {
int num1, num2;
cout << "Enter the range (num1 num2): ";
cin >> num1 >> num2;
int sum = (num2 * (num2 + 1) / 2) - ((num1 - 1) * num1 / 2);
cout << "Sum of numbers in given range: " << sum;
return 0;
}
Output:
Enter the range (num1 num2): 2 4 Sum of numbers in given range: 9
Method 3: Using Recursion
We use recursion to sum numbers from num1 to num2.
#include <iostream>
using namespace std;
int getSum(int num1, int num2) {
if (num1 > num2) {
return 0;
}
return num1 + getSum(num1 + 1, num2);
}
int main() {
int num1, num2;
cout << "Enter the range (num1 num2): ";
cin >> num1 >> num2;
cout << "Sum of numbers in given range: " << getSum(num1, num2);
return 0;
}
Output:
Enter the range (num1 num2): 2 4 Sum of numbers in given range: 9