fork download
  1. // Castulo Jason Quintero CSC5 Chapter 5 homework, pg. 294 #1
  2. //
  3. /**************************************************************************
  4.  * Compute Sum of Numbers
  5.  * ________________________________________________________________________
  6.  * This program will accept user input for a number
  7.  * and will calculate the sum
  8.  * up to the number entered
  9.  * ________________________________________________________________________
  10.  * INPUT
  11.  * numInput : Selected positive integer
  12.  *
  13.  * OUTPUT
  14.  * totalSum : Sum of all integers
  15.  *
  16.  *************************************************************************/
  17. #include <iostream>
  18. using namespace std;
  19.  
  20. int main()
  21. {
  22. // Initialize variables
  23. int numInput, // Selected positive integer
  24. totalSum = 0; // accumulated sum of all numbers
  25.  
  26. // Input - User enters number
  27. cout << "Enter a positive integer number: ";
  28. cin >> numInput;
  29. cout << endl;
  30.  
  31. // While loop to validate input
  32. while(numInput <= 0){
  33. cout << "Only positive integers accepted! ";
  34. cout << "Try again: ";
  35. cin >> numInput;
  36. }
  37.  
  38. // for loop - adds numbers together
  39. for(int i = 1; i <= numInput; i++){
  40. totalSum += i;
  41. }
  42.  
  43. // Display result
  44. cout << "The sum of the numbers from 1 to ";
  45. cout << numInput << " is " << totalSum << endl;
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0.01s 5300KB
stdin
9
stdout
Enter a positive integer number: 
The sum of the numbers from 1 to 9 is 45