tags:

views:

226

answers:

3

what is data(number), if the required output from the following statement is is : AMAZING?

main()
{
 int data;
 if(data!=0 && data==-data)
 {
  printf("AMAZING");
 }
}
+11  A: 

It'd have to be the minimum value of an integer, i.e. 0x80000000 if it's 32-bits, because that's the only number other than zero that remains the same when negated.

#include <stdio.h>

main()
{
 int data = 0x80000000;
 if(data!=0 && data==-data)
 {
  printf("AMAZING");
 }
}

Result:

AMAZING

As Richard Pennington correctly pointed out, this works because of the two's complement representation of negative numbers. The largest representable positive number is one smaller in absolute value than the largest negative number, so if you try to negate the largest negative number it overflows an int and wraps around, giving back the same number.

For computers that use one's complement, every representable number's negative value can also be represented without overflow so this puzzle doesn't have a solution.

Mark Byers
I tried this on my UNIVAC 1100 after adjusting for 36 bit integers (0x800000000) and it didn't work!
Richard Pennington
@Richard, according to Wikipedia for UNIVAC: Numbers were binary with negative values in one's complement. http://en.wikipedia.org/wiki/UNIVAC_1101 So this won't work! It only works in two's complement.
Mark Byers
@Mark: I know. Trick comment. ;-)
Richard Pennington
@Richard, Good input though, I added a bit more explanation to my comment about why and when it works.
Mark Byers
I love the idea of an SO user rushing over to their 30 year old mainframe to try something out.
Daniel Earwicker
Actually, I lied. It wouldn't compile because it wouldn't accept the implicit declaration of main's return value.
Richard Pennington
OK, OK, I admit it. I don't have an 1100. I did use one once, though.
Richard Pennington
finnw
+7  A: 

It depends on the size of an integer and how integers are implemented, but on a two's complement machine with 2 byte integers, the answer is -32768.

Richard Pennington
Well, it is if you're going to go around assuming that CHAR_BIT is 8.
Steve Jessop
A: 

I don't know what the size of int in my machine. so I used a program to find the max value of int like

void main()
{
   int i;
   do{
       }while(i>i++);
   printf ("data=%d",i);
}

I found the max value of i = -2147483648

assign this to data this will work..

chinnagaja
finnw
i am testing this on Borland C++ 5.5.1 for windows 32 on Windows XP machine
chinnagaja
Yea... now i understand my mistake, i really sorry for posting this, totally a big mistake from my end :(
chinnagaja
thanks finnw: now i corrected my mistake and able to achieve result via my own approach
chinnagaja
Hmmmmm, when will people learn (and implement) that `main` returns an `int` to the OS, always.
Thomas Matthews
Thanks Thomas: i learnt the importants of int main in program
chinnagaja