fork download
  1. //Saliha Babar CS1A Chapter 5, Page 294, #1
  2. //
  3. /************************************************************************
  4.  *
  5.  * CALCULATE SUM OF NUMBERS
  6.  * ______________________________________________________________________
  7.  * This program allows user to enter positive number and calculates the
  8.  * sum of all numbers from 1 to number entered
  9.  *
  10.  * Calculation is based on the formula
  11.  * sum = 1 + 2 + ... + until the number entered
  12.  *________________________________________________________________________
  13.  * INPUT
  14.  * userNumber : user choice of positive number
  15.  * count : counter variable for userNumber
  16.  *
  17.  * OUTPUT
  18.  * sum : act as an accumulator
  19.  * sum of number 1 up to the number entered
  20.  * *********************************************************************/
  21.  
  22. #include <iostream>
  23. using namespace std;
  24.  
  25. int main() {
  26. int userNumber; // INPUT - user choice of positive number
  27. int count; // Counter variable
  28. int sum = 0; // Accumulator set to 0
  29.  
  30. // Get the input from the user
  31. cout << "Enter any positive number and I will\n";
  32. cout << "calculate the sum of numbers up to number entered.\n";
  33. cout << "Enter your number below\n";
  34. cin >> userNumber;
  35.  
  36. // Validate user input to only accept positive number
  37. while (userNumber < 0)
  38. {
  39. cout << "You entered negative number\n";
  40. cout << "Enter a postive number only\n";
  41. cin >> userNumber;
  42. }
  43.  
  44. // Start the loop while accumulating the sum tool
  45. for (count = 1 ; count <= userNumber ; count ++)
  46. {
  47. sum += count;
  48. }
  49.  
  50. // Display the output
  51. cout << "The sum of number from 1 to " << userNumber << endl;
  52. cout << "is " << sum << endl;
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0.01s 5296KB
stdin
9
stdout
Enter any positive number and I will
calculate the sum of numbers up to number entered.
Enter your number below
The sum of number from 1 to 9
is 45