Hello,
I'm in a C++ programming class. We were given the assignment to "Write a program that asks the user for a positive integer value. The program should use a loop
to get the sum of all the integers from 1 up to the number entered. For example, if the user
enters 50, the loop will find the sum of 1, 2, 3, 4, ... 50.
Input Validation: Do not accept a negative starting number."
Here is what I have so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int num;
cout << "Enter a positive number:\n";
cin >> num;
for (int x = 0; x <= num; x++)
{
sum = sum + num;
x++;
}
if (num < 1)
{
cout << "\n" << num << " is an invalid input.";
cout << " Please enter a positive integer.\n";
}
else
cout << "\nThe sum of numbers 1 through " << num
<< " " << "is " << sum << endl;
return 0;
}
|
I don't know where I messed up or went wrong, but whenever I enter the number to test the code, I'm not getting the write answer. For instance, whenever I enter "2" the code should tell me 3, but instead it says 4.
Can someone please tell me where I went wrong.