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."
#include <iostream>
usingnamespace 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.
You need to concentrate on this first. This means you should not proceed until the user gives you a positive number. You check to see if the number entered is negative or positive on line 17, but that needs to occur immediately after the user inputs a number and the for-loop you should use needs to occur within the else block of that check.
As far as calculating the number, you need to add the values of x to sum each time instead of num.
Your program flow should look like so:
1. Get input from user.
2. If user inputs a negative number, tell them and do nothing (or keep pestering them until they do as I say :P).
3. Else, loop between [1, num], adding each increment to sum and output result.
Also, because you have an x++; in your for loop, you will be adding every other number, since you are increasing the value of x without using it. Leave that (x++;) out of the loop.
Also, try sum += x; in your loop. At the moment you are adding your input every iteration. For example, when are inputting 2 the code is adding 2+2. Skipping a step inbetween. The code has 3 iterations because you are starting from 0 but going to == num and therefore have num+1 iterations.