Tag Archives: #WSQ04

Homework 4: Sum of Numbers

This program sums a range of consecutive numbers, between a given range by the user. It’s very simple to make, I will show you step by step how to make it.

  1. As usual, you need to call the necessary libraries and open the main function.
  2. We have to declare two variables for the bounds, one for the sum,  and another one that keeps the value of the lower bound. The variable for sum must be inicialized in zero.
  3. Then, we ask the user for the bounds and validate if the lower bound is less than the upper one. If it is, we proceed to sum number by number, increasing the lower bound value one by one, this with a while loop, that will work until the variable ‘L’ is the same as ‘U’ (upper bound).
  4. Finally, we print on the screen the value of the sum made.

 

Here is the code…

#include <iostream>
using namespace std;

int main()
{
  int L,U,l,S=0;

  cout << "I'll give you the sum of a rage of consecutive integer numbers, you only have to indicate the interval\nWhich is the lower bound? ";
  cin >> L;
  cout << "Which is the upper bound? ";
  cin >> U;
  l=L;

  while (L>U)
  {
    cout << "You entered the numbers in the wrong order.\nPlease do it rightly.\n\nLower bound: ";
    cin >> L;
    cout << "Upper bound: ";
    cin >> U;
  }

  while (L<=U)
  {
    S+=L;
    L++;
  }


  cout << "The sum of the consecutive integer numbers between " << l << " and " << U << " is equal to: " << S << endl;
  return 0;
}