fork download
  1. //Devin Scheu CS1A Chapter 5, P. 294, #1
  2. //
  3. /**************************************************************
  4. *
  5. * CALCULATE SUM OF NUMBERS
  6. * ____________________________________________________________
  7. * This program determines the sum of all integers from 1 up to
  8. * a specified positive integer.
  9. *
  10. * Computation is based on a loop summing integers from 1 to n:
  11. * sum = sum + i (where i ranges from 1 to n)
  12. * ____________________________________________________________
  13. * INPUT
  14. * inputNumber : The positive integer up to which the sum is calculated
  15. *
  16. * OUTPUT
  17. * totalSum : The calculated sum
  18. *
  19. **************************************************************/
  20.  
  21. #include <iostream>
  22. #include <iomanip>
  23.  
  24. using namespace std;
  25.  
  26. int main () {
  27.  
  28. //Variable Declarations
  29. int inputNumber; //INPUT - The positive integer up to which the sum is calculated
  30. int totalSum; //OUTPUT - The calculated sum
  31.  
  32. //Prompt for Input
  33. cout << "Enter a positive integer: ";
  34. cin >> inputNumber;
  35.  
  36. //Input Validation
  37. while (inputNumber < 0) {
  38. cout << "\nError: Please enter a non-negative number: ";
  39. cin >> inputNumber;
  40. }
  41.  
  42. //Calculate Sum
  43. totalSum = 0;
  44. for (int i = 1; i <= inputNumber; i++) {
  45. totalSum += i;
  46. }
  47.  
  48. //Output Result
  49. cout << "\n";
  50. cout << left << setw(25) << "Entered Number:" << right << setw(15) << inputNumber << endl;
  51. cout << left << setw(25) << "Sum:" << right << setw(15) << totalSum << endl;
  52.  
  53. return 0;
  54. } //end of main()
Success #stdin #stdout 0.01s 5324KB
stdin
50
stdout
Enter a positive integer: 
Entered Number:                       50
Sum:                                1275