C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - General Questions (Q.No. 2)
2.
How many times the while loop will get executed if a short int is 2 byte wide?
#include<stdio.h>
int main()
{
    int j=1;
    while(j <= 255)
    {
        printf("%c %d\n", j, j);
        j++;
    }
    return 0;
}
Infinite times
255 times
256 times
254 times
Answer: Option
Explanation:

The while(j <= 255) loop will get executed 255 times. The size short int(2 byte wide) does not affect the while() loop.

Discussion:
59 comments Page 2 of 6.

Pavani said:   1 decade ago
The answer is 256 its not 255 because the while loop gets executed when j=255.that is it takes 255 loop.but the while condition is executed untill the condition is failed.

So it fails when j=256.

Singu hemanth said:   1 decade ago
While compilation we get output "The output size is too large (infinite loop or larger text output) ". But the answer was 255 how its possible I can't understood. Help me how its was came.

Viplov said:   1 decade ago
J=1 and while (j <= 255).

J start from 1 to 255 and run only 255 times, it goes to 255 because of <= if this sign is only < then it goes to only 1 to 254 and run only 254 times.

Abhishek said:   10 years ago
char i;
for(i=0;i<255;i++)
{
printf("%c",i);
}

I want to ask that after 255. What will happen? It will go to 0 and continue to run from 1, 2 or will run infinite times?

Nayana said:   1 decade ago
Hi vivek in the program the initital value of j=1 the statement in the while condition will execute until j value will become 255. so the statement will execute 255 times

Vikas kumar said:   9 years ago
Answer is an infinite loop like from range of 0 to 128 then from -1to 128 and goes on repeating and after compiling and executing the program it gives an infinite loop.
(1)

Manu said:   1 decade ago
Hai friends some of you are telling the answer as 225 how you people got that I can't will you explain me. Because am confused in that.

Anyone help me for that.

Karthi said:   1 decade ago
Initial value of j is 1 and the last condition of the while statement is j=225. so the loop get executed 225 times. It does not change according to declaration.

Vishal zadafiya said:   9 years ago
Loop will execute infinite time because int by default signed ao its range is -127 to 128 first it's execute 1 to 128 then 0 to 127 and again start 1 to 128.

Shalini said:   1 decade ago
I think the answer is infinite. Loop continues because in case of characters after 127 next value will be -128. Hence the loop will never come to an end.


Post your comments here:

Your comments will be displayed after verification.