English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

6 answers

AND the number with 0x1, if its true then its odd, if false, then even.

2006-12-25 00:55:51 · answer #1 · answered by justme 7 · 0 0

The above posters who mention bitwise AND have the most efficient/correct answer. Here's the corrected version for above poster's program.

#include
using namespace std;

int main()
{
int i = 0;
cout << "Enter a number: ";
cin >> i;
cout << i << " is an " << (i&1) ? "odd" : "even" << " number." << endl;
return 0;
}

C++ has been revised in 99, hence the iostream, not iostream.h. All the standard functions are in the standard namespace. Hence using namespace std;. Main returns an int, so it's int main, not void main. Drop the conio.h, it's non-standard.

2006-12-25 04:27:07 · answer #2 · answered by csanon 6 · 0 0

The key is the modulo operator (%).

The following code will do:

#include
using namespace std;
int main() {
int x;
cin >> x;
if(x%2) {
cout << x << " is odd";
} else {
cout << x << " is even";
}
return 0;
}

2006-12-24 21:32:16 · answer #3 · answered by joshuaali2000 1 · 0 0

Program that check whether a given number is odd or even:

#include
#include
#include
void main()
{
int i;
clrscr();
cout<<"Enter a Number :";
cin>>i;
if((i/2)==0)
{
cout<<"Its a even number";
}
else
{
cout<<"its a odd number";
}
getch();
}

2006-12-24 21:22:59 · answer #4 · answered by Max Payne 2 · 0 0

Using bitwise AND (&) is MUCH faster than division or modulus.

#include
#include
#include
void main()
{
int i;
clrscr();
cout<<"Enter a Number :";
cin>>i;
cout << i << " is an " << (i&1) ? "odd" : "even" << " number."
getch();
}

2006-12-25 03:59:04 · answer #5 · answered by Steve A 2 · 0 0

Check and see if the modulus of being divided by two is one or zero. If it is one it is odd, if it is zero it is even.

2006-12-24 21:21:44 · answer #6 · answered by Bryan A 5 · 0 0

fedest.com, questions and answers