// ============================================================================ // file: Sample.cpp // ============================================================================ // Programmer: Scott Edwards // Date: 09/15/2014 // Class: CSCI 123 ("Intro to Programming Using C++") // Time: MW 11:00am // Instructor: Mr. Edwards // Project: LoopSum // // Description: // This program is a contrived example to illustrate the coding style // guidelines handout. The user is prompted for a positive integer, which // is used as an upper bound for a loop. Then the sum of all integers // from one to the upper bound is calculated and displayed to the standard // output stream. // // ============================================================================ #include #include using namespace std; // function prototypes int CalcSum(int limit); bool IsValidInt(int value); // ==== main ================================================================== // // ============================================================================ int main() { bool bIsValid; int sum; int upperBound; // get the upper bound from the user cout << "Please enter a positive integer value: "; cin >> upperBound; // make sure the value is valid bIsValid = IsValidInt(upperBound); if (false == bIsValid) { cout << "Sorry, you must enter a positive value\n"; exit(EXIT_FAILURE); } // calculate the sum from one to the upper bound sum = CalcSum(upperBound); // display the results to stdout cout << "The sum is " << sum << endl; return 0; } // end of "main" // ==== CalcSum =============================================================== // // This function calculates the sum from one to the limit parameter // (inclusive), then returns the value to the caller. // // Input: // limit [IN] -- an integer value containing the upper bound for the // calculation of the sum // // Output: // The sum of all integers from one to the value of the limit parameter. // // ============================================================================ int CalcSum(int limit) { int counter; int total; for (counter = 1, total = 0; counter <= limit; ++counter) { total = total + counter; } return total; } // end of "CalcSum" // ==== IsValidInt ============================================================ // // This function tests the input value to make sure that it is positive. If it // is, a value of "true" is returned; else, a value of "false" is returned. // // Input: // value [IN] -- an integer value to be tested // // Output: // A value of "true" is returned if the input parameter is positive, // otherwise a value of "false" is returned. // // ============================================================================ bool IsValidInt(int value) { bool bRetVal; // if the input value is less than zero, return "false", else return "true" if (value < 0) { bRetVal = false; } else { bRetVal = true; } return bRetVal; } // end of "IsValidInt"