fork download
  1. //Timothy Price CS1A CH5 Challenge 1
  2. /*******************************************************************************
  3.  * Calculate total
  4.  *
  5.  * This program receives a number and calculates the total of all previous
  6.  * numbers up to the selected number.
  7.  *
  8.  * Inputs:
  9.  * Positive number
  10.  *
  11.  * Output:
  12.  * Sum of numbers
  13.  ******************************************************************************/
  14.  
  15. #include <iostream>
  16.  
  17. using namespace std;
  18.  
  19. int main() {
  20.  
  21. // Data dictionary:
  22. int number; // The number must be positive
  23. int sum = 0;
  24.  
  25. // Program asks for a positive value, and gives choice feedback:
  26. cout << "Enter a positive integer value: " << endl;;
  27. cin >> number;
  28. cout << "You have entered the number " << number << "." << endl;
  29.  
  30. // Rejection for invalid input:
  31. if (number <= 0) {
  32. cout << "Invalid input. Please enter a positive integer: " << endl;
  33. }
  34. // For valid input:
  35. if (number > 0) { // Loop crated to calculate sum of all numbers:
  36. for (int base = 1; base <= number; ++base) {
  37. sum += base;
  38. }
  39. // Display sum:
  40. cout << "The sum of all numbers between 1 and " << number << " is ";
  41. cout << sum << "." << endl;
  42. }
  43. return 0;
  44. }
Success #stdin #stdout 0.01s 5328KB
stdin
15
stdout
Enter a positive integer value: 
You have entered the number 15.
The sum of all numbers between 1 and 15 is 120.