Program to find the sum of numbers in a given range in C++
Program to find the Sum of Numbers in a given range
Here we will discuss how to find the Sum of Natural Numbers in a range defined by user using c++ programming language.
All the positive integers (1, 2, 3, 4…) are the Natural Numbers.
To find the sum of N Natural Numbers we will use a simple loop with condition based on the range defined by the user.
Let’s see how the code works:
- User gives two inputs.
- Inputs are stored in two int type variable say lower_limit and upper_limit.
- A loop is started
- Sum is incremented by i (initialised from lower_limit) in every cycle.
- i is incremented by 1 in every loop cycle.
- Loop will operate until i is equal to upper_limit.
- sum is printed being the sum of Natural Numbers between lower_limit and upper_limit.
//Sum of Natural Numbers in a given range
using namespace std;
int sum=0 , upper_limit,lower_limit;
cout<<"Enter the lower limit: ";
cout<<"Enter the upper limit: ";
//calculating sum of numbers in the given range
cout<<"The Sum of Natural Numbers from "<<lower_limit<<" to "<<upper_limit<<" is "<<sum;
Enter the lower limit: 19
Enter the upper limit: 65
The Sum of Natural Numbers from 19 to 65 is 1974