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.

Working

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.
Program to find the Sum of numbers in a given range

C++ Code

//C++ Program
//Sum of Natural Numbers in a given range
#include<iostream>
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: 19
Enter the upper limit: 65
The Sum of Natural Numbers from 19 to 65 is 1974

Please Login/Signup to comment