Thread: Even & odd number

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    99

    Even & odd number

    program with % operator
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        int number;
    
    
        printf("Enter an integer: ");
        scanf("%d", &number);
    
    
        if(number % 2 == 0)
            printf("Even number is %d.", number);
        else
            printf("Odd number is%d.", number);
    
    
        return 0;
    }
    Enter an integer: 11
    Odd number is 11.

    Program with division operator

    Code:
    #include <stdio.h>
    int main(void)
    {
        int number;
    
    
        printf("Enter an integer: ");
        scanf("%d", &number);
    
    
        if(number / 2 == 0)
            printf("Even number is %d.", number);
        else
            printf("Odd number is %d.", number);
    
    
        return 0;
    }
    Enter an integer: 11
    Odd number is 11.

    Both program's give same output but they use different operator.

    Which one programs is better and why this one is better

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    The second program will only ever recognize zero as even, and nothing else. That is because every division has two results, the quotient and the remainder. The "/" operator gives you the quotient and the "%" operator gives you the remainder. The remainder is what allows you to categorize the number as even or odd. You can do it with the quotient alone but it's a different operation:
    Code:
    if ((number/2)*2 == number)
        printf("Even number is %d.", number);
    else
        printf("Odd number is %d.", number);
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Jul 2002
    Posts
    33
    number is an int. number / 2 will not give you a remainder .
    Last edited by joemccarr; 01-26-2018 at 07:12 AM.

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Actually, that is the point, and I think Greaper knows that. If int gave a remainder, then number/2*2 == number would always be true, which is less than useful.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 12-01-2017, 12:42 PM
  2. Replies: 6
    Last Post: 11-11-2017, 01:26 AM
  3. Replies: 2
    Last Post: 09-30-2015, 09:15 AM
  4. Convert 8-digit Binary Number to decimal number
    By yongsheng94 in forum C++ Programming
    Replies: 2
    Last Post: 07-06-2013, 09:47 AM
  5. Allocation of major number and minor number linux
    By vinayharitsakp@ in forum Linux Programming
    Replies: 4
    Last Post: 12-08-2007, 02:01 PM

Tags for this Thread