Home > Net >  Program that determines if a number is odd or even shows the wrong output if number is longer than 5
Program that determines if a number is odd or even shows the wrong output if number is longer than 5

Time:11-16

If I enter a number that's more than 5 digits long, it shows the wrong number. For example:

Enter Integer: 123456
-7616 is EVEN.-7616 is ODD.

My teacher wants us to use Turbo C but it sometimes freezes for me after I run a program so I used OnlineGDB (https://www.onlinegdb.com) (language: C (TurboC)) instead. Here is my code:

#include <stdio.h>
#include <conio.h>

int number;

int main()
{
    clrscr();
    
    printf("Enter Integer: ", number);
    scanf("%d", &number);
    
    if ((number%2)==0)
    {
        printf("%d is EVEN.", number);
    }
    
    printf("%d is ODD.", number);
    
    getch();
    return(0);
}

CodePudding user response:

It looks like int is a 16-bit integer. 123456 is greater than the 16-bit signed integer limit (32767), so scanf() can’t put the whole number into number. Instead, it gets truncated. 123456 is represented in binary as 11110001001000000. That’s 17 bits, but only the last 16 can fit in number. With the leftmost bit gone, we have 1110001001000000, which is -7616 in two’s complement form (which is what an integer uses).

Try using a larger integer type, like long.

As others suggested in the comments, you may want to put the printf() for odd numbers in an else.

  • Related