fork download
  1. //Amari Mosley CSC5 Chapter 5, P. 294, #1
  2. //
  3. /**************************************************************
  4. *
  5. * COMPUTE SUM OF NUMBERS
  6. *____________________________________________
  7. * This program asks the user for a positive integer value
  8. * and uses a loop to find the sum of all integers from 1 up
  9. * to the number entered, with input validation to reject
  10. * negative starting numbers.
  11. *
  12. * INPUT
  13. * number : Positive integer entered by the user
  14. *
  15. * OUTPUT
  16. * sum : Sum of all integers from 1 up to the entered
  17. * number
  18. *
  19. **************************************************************/
  20.  
  21. #include <iostream>
  22.  
  23. using namespace std;
  24.  
  25. int main() {
  26. // INPUT
  27. int number;
  28.  
  29. // OUTPUT
  30. int sum = 0;
  31.  
  32. // Initialize Program variables / Input Validation Loop
  33. cout << "Enter a positive integer value: ";
  34. cin >> number;
  35.  
  36. while (number < 0) {
  37. cout << "Error: Do not accept a negative starting number.\n";
  38. cout << "Enter a positive integer value: ";
  39. cin >> number;
  40. }
  41.  
  42. // Compute Sum of Numbers using a loop
  43. for (int i = 1; i <= number; i++) {
  44. sum += i;
  45. }
  46.  
  47. // Output Result
  48. cout << "The sum of all integers from 1 up to " << number << " is " << sum << "." << endl;
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0s 5316KB
stdin
11
stdout
Enter a positive integer value: The sum of all integers from 1 up to 11 is 66.