fork download
  1. //Nicolas Ruano CS1A Chapter 5, P. 294, #1
  2. //
  3. /**************************************************************
  4. *
  5. * COMPUTE THE SUMMATION OF INTEGERS FROM ONE TO A GIVEN LIMIT.
  6. * _____________________________________________________________
  7. * This program computes the sum of all consecutive integers from
  8. * one (1) up to a user-specified limit. It prompts the user to
  9. * enter a positive whole number and, if a negative value is
  10. * provided, repeatedly requests a valid entry. Once a positive
  11. * number is entered, the program uses a loop to add each number
  12. * from one to * the specified limit and then displays the
  13. * accumulator result to the user.
  14. *
  15. * Computation is based on the formula:
  16. * Natural numbers Sigma from 0 to the user’s specified index.
  17. * ____________________________________________________________
  18. * INPUT
  19. * number
  20. *
  21. *
  22. * OUTPUT
  23. * sum
  24. *
  25. **************************************************************/
  26. #include <iostream> // For input and output
  27.  
  28. using namespace std;
  29.  
  30. int main() {
  31. int number; // Variable to store user input
  32. int sum = 0; // Variable to store the total sum
  33.  
  34. // --- Step 1: Ask for a positive number ---
  35. cout << "Enter a positive number: 1\n";
  36. cin >> number;
  37.  
  38. // --- Step 2: Input Validation Loop ---
  39. while (number < 0) {
  40. cout << "Please enter a positive number: 50\n";
  41. cin >> number;
  42. }
  43.  
  44. // --- Step 3: Calculate the Sum using a loop ---
  45. for (int i = 1; i <= number; i++) {
  46. sum = sum + i; // Add each number to the sum
  47. }
  48.  
  49. // --- Step 4: Display the result ---
  50. cout << "The total sum is: 60\n" << sum << endl;
  51.  
  52. // --- Step 5: End Program ---
  53. return 0;
  54. }
  55.  
  56.  
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
Enter a positive number: 1
The total sum is: 60
243421080