Program to find the sum of numbers in a given range in C++

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.

Algorithm:-

  1. Take two inputs.
  2. Inputs are stored in two int type variable say lower_limit and upper_limit.
  3. Initialize i to lower_limit
    1. i=lower_limit
  4. Initialize sum to 0
  5. run a for loop till i is less than or equal to upper_limit, i<=upper_limit
    1. update sum +=i
    2. increment i by 1 in every iteration
  6. sum is printed being the sum of Natural Numbers between lower_limit and upper_limit.

C++ Code

#include
using namespace std;
    //main Program
int main()
{
    int sum = 0 , upper_limit, lower_limit;
    cout << "Enter the lower limit: ";
    cin >> lower_limit;
    cout << "Enter the upper limit: ";
    cin >> upper_limit;
    
        //calculating sum of numbers in the given range
    for(int i = lower_limit; i <= upper_limit; i++)
    {
        sum += i;
    }

        //printing output
    cout<<"The Sum of Natural Numbers from " << lower_limit << "to "<< upper_limit << " is "<< sum;
        return 0;
}

Output

Enter the lower limit: 5
Enter the upper limit: 7
The Sum of Natural Numbers from 5to 7 is 18