#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i = 0; i <= positiveInteger; i++)
{
if ( positiveInteger >= 0 )
{
result += i;
}
else
{
cout << "Please input a positive integer." << endl;
}
}
cout << result;
return 0;
}
Above I have a for loop with an if else statement in the center. I am confused because I want it to be so when I enter a integer that is not negative it will loop the if result. But I want it to be so if I put in a negative number it says please input a positive integer. That’s why I set it so in the if statement only numbers above and = to 0 would return the result, but if I enter a negative number I just get 0 I want it to say “Please input a positive integer”. I don’t understand what I’m doing wrong. Isn’t the if statement if true pulls the if and if its not true pulls the else? Or am I missing something?
If I got it right, you want to
1. input a number;
2.1 If the number is positive you loop through it.
2.2 If it’s negative you show the error message.
The problem is your loop, where the conditional is, checks if i (which is zero) is smaller then the number. However if you input a negative number i will be bigger then positiveInteger and you won’t loop through the if. I fixed your code