Code not working? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Code not working?

Hello, there seems to be a problem with this, and i'm not sure what it is. thank you for answers! It keeps repeating "0 is even" when i press run. #include <iostream> using namespace std; int main() { for (int x=0; x<=10; x++) { if (x= 0, 2, 4, 6, 8, 10) { cout << x << " is even" ; } else { cout << x << " is odd" ; } } }

6th Jan 2017, 1:19 AM
YaySushi
5 Answers
+ 7
I'm not good with C++ but I probably can help. #include <iostream> using namespace std; int main() { for (int x=0; x<=10; x++) { if (x % 2 == 0) { cout << x << " is even" ; } else { cout << x << " is odd" ; } } }
6th Jan 2017, 2:20 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 2
The problem is your if, you set x to 0 with x = 0. To compare numbers use == EDIT: I don't know what the rest of the if is supposed to do, but if you want to make it work for all even numbers make it if(x%2){/*x odd*/}else{/*x even*/}
6th Jan 2017, 1:31 AM
Robobrine
Robobrine - avatar
+ 2
1.= is assignment operator. you should you equality check operator ==. 2.x℅2==0 for even. 3.return 0 at the end #include <iostream> using namespace std; int main() { for (int x=0; x<=10; x++) { if (x℅2==0) { cout << x << " is even" ; } else { cout << x << " is odd" ; } } return 0; } or else #include <iostream> using namespace std; int main() { for (int x=0; x<=10; x++) { if (x==0||x==2||x==4||x==6||x==8||x==10) { cout << x << " is even" ; } else { cout << x << " is odd" ; } } return 0; }
6th Jan 2017, 2:51 AM
Megatron
Megatron - avatar
+ 1
your main problem is that you initialized x as 0 but dont tell it when to ++. And since there is no x++; i your loop the loop never ends and x is constantly 0. because x is always less than 10 the loop never ends
6th Jan 2017, 11:15 AM
Edwin
0
Thank you very much for the answers, it works and I understand it now :)
6th Jan 2017, 3:50 PM
YaySushi