Tuesday, December 6, 2016

Programming Challenge 5.1 - Sum Of Numbers

/* Sum Of Numbers - This program asks the user for a positive integer value. The
program uses a loop to get the sum of all the integers from 1 up to the number
the user entered.

Example: If the user enters 50, the loop will find the sum of 1, 2, 3, .... 50.

Input Validation: No negative values are accepted. */

#include "Utility.h"

int main()
{
    /* Variables: Number, Sum */
    int number,
        sum = 0;

    /* Ask the user for a number */
    cout << "Enter a positive number, and i will tell you the sum of all numbers.\n"
        << "Please enter a number: ";
    cin >> number;

    /* Validation: Check if the number entered is positive. If so, enter the loop */
    if (number != -1)
    {
        /* For Loop: minNum is declared and initialized in the loop header as starting
           value. As long as the starting value is smaller or equal to the number the
           user entered, the loop will iterate */
        for (int minNum = 1; minNum <= number; minNum++)
        {
            /* Calculation: The numbers are added, and the result stored in
               the variable sum */
            sum += minNum;
        }
        /* Display the result */
        cout << "The sum total of numbers 1" << " through "
            << number << " is " << sum << endl;
    }
    else
    {
        /* Error message */
        cout << "You entered an invalid number, only positive numbers are allowed.\n";
    }

    pauseSystem();
    return 0;
}

No comments:

Post a Comment