fork download
  1. //Ryan Shahriyarpour CS1A Carl Argila CH5 HW Q:1
  2. //
  3. /*****************************************************************************
  4.  *
  5.  * Sum of Numbers
  6.  *
  7.  *********************
  8.  *
  9.  * The program asks the user for a positive integer value. The program uses
  10.  * a loop to get the sum of all the integers from 1 up to the number entered.
  11.  * For example, if the user enters 50, the loop will find the sum of
  12.  * 1, 2, 3, 4, to 50.
  13.  *
  14.  * INPUT
  15.  * num : A positive integer entered by the user
  16.  *
  17.  * OUTPUT
  18.  * sum : The sum of all integers from 1 to num
  19.  *
  20.  ****************************************************************************/
  21.  
  22. #include <iostream>
  23. using namespace std;
  24.  
  25. int main()
  26. {
  27. int num;
  28. int sum = 0;
  29.  
  30. cout << "Enter a positive integer: ";
  31. cin >> num;
  32.  
  33. // Input validation
  34. if (num < 1)
  35. {
  36. cout << "Error: Please enter a positive integer.\n";
  37. return 0;
  38. }
  39.  
  40. // Calculate the sum
  41. for (int i = 1; i <= num; i++)
  42. {
  43. sum += i;
  44. }
  45.  
  46. cout << "The sum of 1 through " << num << " is " << sum << endl;
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Enter a positive integer: The sum of 1 through 21918 is 240210321