while loop only running once?

Hi, I think my problem is the while loop is only running once but I am confused as to how to fix it... Not 100 % sure that's the problem I am very beginner
#include <iostream>
#include <string>
using namespace std;
string evenOrOdd (int number) {
string answer;
if ((number % 2) == 0) {
answer = "Even";
}
else {
answer = "Odd";
}
return answer;
}

int main () {
string answer;
int number = 1;
while (number != 0) {
cout << "Enter a number: ";
cin >> number;
cout << number;
cout << endl;
if (number != 0) {
answer = evenOrOdd (number);
cout << number << " is " << answer << endl;
}
if (number = 0) {
cout << "Good bye!";
}
}
return 0;
}
Launch Terminal
0001: Enter~a~number:~11
0002: 11~is~Odd
0003: [NONE]


=================== MISMATCH FOUND ON LINE 0003: ===================
ACTUAL : [NONE]
EXPECTED: Enter~a~number:~12
======================================================

Adjust your program and re-run to test.




Test 1 failed
yes, it only runs once because you assign it to zero:
if(number = 0) {

that should be ==, the test for equality, not an assignment statement (single =).
Last edited on
You have written if (number = 0) it should be if(number == 0).
= is for assigning and == is for comparing, remember ;).

What is happening is that first number is set to 0 inside the if condition and the condition then evaluates number which would return false.

It's one of the most common mistakes done by new programmers.


Try using if(!number) instead of if(number == 0) to check if an integer is 0. if(!number) will return true if number is zero otherwise false.

This is because 0 represents false and anything else represents true.


Oh and in the future please use coding tags (http://www.cplusplus.com/articles/jEywvCM9/) it helps the readers A LOT.
Last edited on
Thank you for pointing out that I was not using coding tags! And thank you for the explanation!
Topic archived. No new replies allowed.