Question:

In C++ if you wanted to find an even or odd number you would...?

by  |  earlier

0 LIKES UnLike

go like

if(num%=0) ?!

how do u use % in that line? and i know that is wrong^^ how would u set it up though.

 Tags:

   Report

6 ANSWERS


  1. I think you would compare 'num % 2' to zero.  If true, the number is even.  % is the 'modulus' operator.

    [edit]

    When it says 'not an lvalue', it means that you can't *assign* 0 to 'num%2'.  Note that it would have been better if you hadn't left out the '2' in the example of what you tried.

    '=' is ASSIGNMENT.  if you want to compare to 0, you have to use '=='.


  2. if (a%2 == 0) {

      printf ("a is even.\n");

    }

    else {

      printf ("a is odd.\n");

    }

    Hope this helps.

  3. the % is the mod operator, it is used like this:

    num%2

    it will return the remainder of num divided by 2.

    so in your case:

    if(num%2 == 0)

    {

    printf("%d is positibe", num);

    }

  4. if(num%=0) ?!

    you are using assignment operator ( = ) ...

    you are not assigning to to 0....

    use bo0lean  which is ( == ) not an assignment operator which is ( = )

    if(num % 2 == 0){

       printf("Even");

    }

    else{

       printf("Odd");

    }

  5. if you dont know this, you should be using C, not C++.

    .........................................

    sorry,

    is it sumthin like...

    int num;

    {

    if(num/2==false) ;       /* if the number divided by 2 doesnt work... */

    then();

    else();

    }

  6. Using % is incredibly inefficient and idiotic.  Whoever taught you that method is an idiot.  If I were to do this with C/C++ or Assembly Language, I would do it like this:

    Look at the test number as a binary number.

    If the test number is odd, then bit 0 (the right-most bit) would be 1.

    Using the bitwise AND function, we can test if bit 0 is set.  Just do a bitwise AND with 1 and you can see this.



    8 bit number examples:

    00000010  test number (2 in decimal)

    AND

    00000001

    =0 (the number is even)

    00000101 test number (5 in decimal)

    AND

    00000001

    = 1 (the number is odd)

    C/C++ Example:

    unsigned int testnum=5;

    if (testnum & 1)

    {

    // code executes if number is odd

    }

    or you can do this:

    if (!testnum & 1)

    {

    // code executes if number is even

    }

Question Stats

Latest activity: earlier.
This question has 6 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions