fork download
  1. //Cameron Pham CS1A Chapter 5, p. 294, #1
  2. //
  3. /******************************************************************************
  4. * CALCULATE SUM OF NUMBERS
  5. * ______________________________________________________________________________
  6. * This program accepts a positive integer value and performs a loop to compute
  7. * the sum of all integers from 1 up to the value accepted.
  8. * ______________________________________________________________________________
  9. * INPUT
  10. * Integer // Positive integer value
  11. *
  12. * OUTPUT
  13. * Sum // Sum of all the integers from 1 up to the number entered.
  14. *******************************************************************************/
  15. #include <iostream>
  16. using namespace std;
  17.  
  18. int main()
  19. {
  20. //Initalize Variables
  21. int integer;
  22. int sum;
  23.  
  24. //Ask the user to enter a value.
  25. cout << "Please enter a value, and I will calculate the sum of all the";
  26. cout << " integers from 1 up to the number you have entered.";
  27. cin >> integer;
  28. cout << endl << "You have entered " << integer << "." << endl;
  29.  
  30. //Validate the input.
  31. while (integer < 0)
  32. {
  33. cout << "Your input cannot be a negative number. Please try again! ";
  34. cin >> integer;
  35. }
  36.  
  37. //Calculate the sum.
  38. for (int count = 1; count <= integer; count++)
  39. {
  40. sum += count;
  41. }
  42.  
  43. //Display the sum.
  44. cout << "The sum of the integers from 1 to " << integer << " is " << sum << ".";
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0.01s 5320KB
stdin
40
stdout
Please enter a value, and I will calculate the sum of all the integers from 1 up to the number you have entered.
You have entered 40.
The sum of the integers from 1 to 40 is 820.