C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - Find Output of Program (Q.No. 4)
4.
What will be the output of the program?
#include<stdio.h>
int main()
{
    unsigned int i = 65535; /* Assume 2 byte integer*/
    while(i++ != 0)
        printf("%d",++i);
    printf("\n");
    return 0;
}
Infinite loop
0 1 2 ... 65535
0 1 2 ... 32767 - 32766 -32765 -1 0
No output
Answer: Option
Explanation:

Here unsigned int size is 2 bytes. It varies from 0,1,2,3, ... to 65535.

Step 1:unsigned int i = 65535;

Step 2:
Loop 1: while(i++ != 0) this statement becomes while(65535 != 0). Hence the while(TRUE) condition is satisfied. Then the printf("%d", ++i); prints '1'(variable 'i' is already incremented by '1' in while statement and now incremented by '1' in printf statement) Loop 2: while(i++ != 0) this statement becomes while(1 != 0). Hence the while(TRUE) condition is satisfied. Then the printf("%d", ++i); prints '3'(variable 'i' is already incremented by '1' in while statement and now incremented by '1' in printf statement)
....
....

The while loop will never stops executing, because variable i will never become '0'(zero). Hence it is an 'Infinite loop'.

Discussion:
17 comments Page 2 of 2.

Abi said:   1 decade ago
Unsigned integer value is only 65535. How the loop is execute in infinite?

Adarsh said:   1 decade ago
@Aparna.

Its because your compiler supports 65535 +, so during program execution, you will have increment of 2 in original value of 65535 (1 due to while condition, and 1 due to printf condition).

Hence output will be 655376553965541.

Aparna.v said:   1 decade ago
I can understand that this loop runs infinitely but why is it printing 1 2 3 and so on?

AnkitS said:   1 decade ago
Your compiler might NOT be 16-bit. Means, int is not 16 bits but 32 bits (4 bytes). That is why, it is going beyond 65535.

Coder said:   1 decade ago
The loop is infinite but the output is strange, and not as expected,

The output I am getting, after running this code is - 655376553965541655436554565547655496555165553655556555765559655

Although, our expectation is that compiler must switch to 0, if we increment 65535 (beyond the upper range of unsigned int). but it's printing beyond the limit like 65537, and then 65539.

What exactly happening ?

Rupinderjit Singh said:   1 decade ago
Because when the upper limit of the unsigned int gets over,it again roll over to 0 and moves onward (that is:0 1 2 3 . . . 65534 65535 0 1 2 3 4 . . . .)

Livya said:   1 decade ago
Hi

if the program changed to :
#include<stdio.h>
int main()
{

unsigned int i = 65535; /* Assume 2 byte integer*/
while(i++ != 65539)
printf("%d",++i);
printf("\n");
return 0;
}
the output is "6553765539" not 13..... why this happened?


Post your comments here:

Your comments will be displayed after verification.