Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

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.

Program to find the Sum of numbers in a given range

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:-

    
    //C++ Program
    //Sum of Natural Numbers in a given range
    #include<iostream>
    using namespace std;
    //main Program
    int main()
    {
        int sum = 0 , upper_limitlower_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_limiti <= upper_limiti++){
        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