C Programming - Control Instructions - Discussion
Discussion Forum : Control Instructions - Find Output of Program (Q.No. 6)
6.
What will be the output of the program, if a short int is 2 bytes wide?
#include<stdio.h>
int main()
{
short int i = 0;
for(i<=5 && i>=-1; ++i; i>0)
printf("%u,", i);
return 0;
}
Answer: Option
Explanation:
for(i<=5 && i>=-1; ++i; i>0) so expression i<=5 && i>=-1 initializes for loop. expression ++i is the loop condition. expression i>0 is the increment expression.
In for( i <= 5 && i >= -1; ++i; i>0) expression i<=5 && i>=-1 evaluates to one.
Loop condition always get evaluated to true. Also at this point it increases i by one.
An increment_expression i>0 has no effect on value of i.so for loop get executed till the limit of integer (ie. 65535)
Discussion:
49 comments Page 3 of 5.
Nemichand said:
1 decade ago
When the value of i is 6, then how loop work? because statement is
(i<=5 && i>=-1)
Here must be true both condition.
(i<=5 && i>=-1)
Here must be true both condition.
Stliya said:
8 years ago
@Shilpa.
You are wrong. If it is %d then infinite loop. It is % you so answer option A is correct. Loop terminates at 65535.
You are wrong. If it is %d then infinite loop. It is % you so answer option A is correct. Loop terminates at 65535.
Nandy said:
1 decade ago
@Zooglw: here ++i statement act as conditional statement .it's nt a inc/dec statement.so it has no effect on the for loop
Sai said:
1 decade ago
If you compile the code in gcc, the output will be different.
After 32767, it is printing from 4294934528 to 4294967295.
After 32767, it is printing from 4294934528 to 4294967295.
Sandeep said:
6 years ago
What happens after i value is greater than 65535, is loop terminated or 0 will be printed resulting in an infinite loop.
Vikas said:
1 decade ago
Here i is declared as short int not unsigned int. Is it right that i counts 0 to 65535 instead of -32768 to 32757 ???
Aakash said:
1 decade ago
@mano ,,bravo ,but u said (0<=5&&0>=-1 is initialization but how loop can be incremented by i>o
Sundar said:
1 decade ago
I have tested the give program. It prints 1 ... to 65535.
But it takes some time to completely print all values.
But it takes some time to completely print all values.
Ankit kumar said:
9 years ago
Here is a syntax error, as the place of loop condition and increment have been interchanged.
Anil said:
1 decade ago
%u returns the address of specified variable here that variable is i.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers