Hello everyone, i was hoping someone could clarify as to why my code isn't working. I'm fairly new to c++ and didn't know who else to ask.
If i'm doing anything wrong in my code lines please let me know as i'm willing to learn.
This is what i have so far. For some reason when i run in on Dev it really doesn't do anything.
Purpose of this code is for user to input a number and for program to output all the odd numbers.
#include <iostream>
usingnamespace std;
int main(){
int number, z;
cout<<"Please Enter A Number"<<endl;
cin>>number;
while (number>0){
z=number%2;
if (z>1){
cout<<number<<" "<<endl;
number=number-1;
}
else{
number=number-1;
}
}
return 0;
}
After line 10, z will be either 0 or 1. The modulo(%) operator returns the remainder after division.
If the number is even, z will be zero. Any even number divided by two will yield a remainder of zero.
If the number is odd, z will be one. Odd numbers cannot be evenly divided by 2, so there will always be a remainder.
If z is always zero or one, then line 12's condition will always be false. Z GREATER THAN 1 cannot happen. Print something in your else case, and you'll see that it is this case that always runs.
#include <iostream>
usingnamespace std;
int main(){
int number, z;
cout<<"Please Enter A Number"<<endl;
cin>>number;
while (number>0)
{
z=number%2;
if (z != 0){
cout<<number<<" "<<endl;
number=number-1;
}
else{
number=number-1;
}
}
return 0;
}
Now this code should work perfectly fine. If you want to learn more, i would recommend the following article.
i appreciate the help, i should have ran this code in my head to see if it made logical sense. :D
thank you though. Apparently i don't even need "!=" all i need is to make line 13 into z>0 for it to work. i'm still testing to see if this works for most cases.
all i need is to make line 13 into z>0 for it to work
You don't even need that. You can just say if (z) {....
There are many other improvements possible:
1 2 3 4 5 6
// Use for construct to express loopiness
for (; number>0; --number) {
if (number%2) {
cout<<number<<'\n'; // use \n instead of endl. No space required.
}
}