fork download
  1. //Eun Hyeung Lucia Lee CSC5 Chapter 5, P. 295, #1
  2. //
  3. /**************************************************************
  4.  * CALCULATE SUM
  5.  * ____________________________________________________________
  6.  * This program prompts the user for a positive integer value.
  7.  * The program then computes the sum of all the integers from
  8.  * 1 to the input integer.
  9.  *
  10.  * No negative starting numbers are accepted.
  11.  * ____________________________________________________________
  12.  * INPUT
  13.  * max_num : Positive integer that will be
  14.  * used as max for sum
  15.  *
  16.  * OUTPUT
  17.  * sum : Sum of all integers added to the
  18.  * max_num
  19.  * PROCESSING
  20.  * count : Counter integer set to 1 that
  21.  * controls the loop by comparison
  22.  * to the max_num
  23.  **************************************************************/
  24. #include <iostream>
  25. using namespace std;
  26.  
  27. int main()
  28. {
  29. // Define variables
  30. int count; // PROCESSING - Counter for loop
  31. int max_num; // INPUT - Positive integer used as max
  32. int sum = 0; // OUTPUT - Total sum of all integers based on max
  33.  
  34. // Ask for user input
  35. cout << "Please enter a positive integer: " << endl;
  36. cin >> max_num;
  37.  
  38. // For invalid inputs (negative)
  39. while (max_num <=0)
  40. {
  41. cout << "<Error: Please input a POSITIVE integer>" << endl;
  42. cin >> max_num;
  43. }
  44.  
  45. // For valid inputs
  46. for (count = 1; count <= max_num && max_num >= 1; count++)
  47. {
  48. // Display sums
  49. cout << count << " + " << sum << " = ";
  50. sum += count;
  51. cout << sum << endl; // Updated sum
  52. }
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 4460KB
stdin
-5
5
stdout
Please enter a positive integer: 
<Error: Please input a POSITIVE integer>
1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
4 + 6 = 10
5 + 10 = 15