C# Programming Questions and Answers
Select the output for the following set of code:
staticvoid Main(string[] args)
{
float s = 0.1f;
while(s <= 0.5f)
{
++s;
Console.WriteLine(s);
}
Console.ReadLine();
}
for the first while condition check when s = 0. If it is true as control goes inside loop ++s increments value of s by 1 as 1+0.1 = 1.1. So, for next condition while loop fails and hence, prints final value of s as 1.1.
Output: 1.1
Select the output for the following set of code :
staticvoid Main(string[] args)
{
int i, j;
for(i =1; i <=3; i++)
{
j =1;
while(i % j ==2)
{
j++;
}
Console.WriteLine(i +" "+ j);
}
Console.ReadLine();
}
Since, condition never satisfied for any value of i and j for which (i % j == 2).Hence, j is always constant ‘1’ and ‘i’ increments for i = 1, 2, 3.
Output: 11 21 31.
Select the output for the following set of Code:
staticvoid Main(string[] args)
{
int i;
i =0;
while(i++<5)
{
Console.WriteLine(i);
}
Console.WriteLine("\n");
i =0;
while(++i <5)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
for while(i++ < 5) current value of 'i' is checked first and hence prints incremented value afterwards.So, i =1, 2, 3, 4, 5.But, for while(++i < 5) current value is incremented first and then checks that value with given condition and hence then prints that value.So, i = 1, 2, 3, 4. Output: 1 2 3 4 5 1 2 3 4