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 3 of 6.

Diana said:   1 decade ago
Sangeetha,the range of short signed int is from -32768 to +32767.So,it won't wrap around.You are confusing it with char whose range is from -128 to +127.

Lalitha said:   1 decade ago
Simple,

It is in case of <= increment by 0ne of right side of the condition and then decrement it by left value;
1<=255 True
So,
(255+1)-1=255

Rachit said:   1 decade ago
Loop will execute from j=0 to 224 at j=225 loop will terminated so it will execute upto 225 times from 0 to 224.

I think it makes it more clear.

Fanta said:   1 decade ago
The body of the while loop will execute 255 times. But the while condition will execte one more time to became condition false.

It takes 256.

Vishal Naik said:   1 decade ago
Do it manually for a shorter number, ex while(j <= 3), you will get the answer as 3. Similarly when while(j <= 255), Answer is 255.

Dhronan said:   1 decade ago
@fanta

you are right but see they didn't say while statement, they said while loop, so you ought consider the whole loop statements.

Saswati said:   1 decade ago
I coudnt undrstand "%c %d". and also this "j,j" . why two js are used ? have anyone checked output using compiler?

Swathi said:   1 decade ago
%c %d means short integer, according to this concept it won't affect while.

Hence while loop get executed by 255 times...understand.

Vibhan said:   10 years ago
Sorry friends but get excited 256 because it check while loop at the time when j value is 256. So while statement execute 256 times.

DEEPak said:   1 decade ago
In question 1, while loop will execute 256 times. 1 time also for false condition. But the body will execute only 255 times only.


Post your comments here:

Your comments will be displayed after verification.