predict the output of the following(and after that say how the answer is coming) :-
1)
class dk1
{
public static void main (String args[])
{int i;
for(i=-1;i <10;i++)
{
System.out.println(++i);
}
}
}
2)
class dk2
{
public static void main (String args[])
{
int i=2,k=1;
while(++i<6)
k*=i;
System.out.println(k);
}
}
3)
class dk3
{
public static void main (String args[])
{
int m=2,n=15;
for (int i =1;i<=5;i++)
{
m++;--n;
System.out.println("m="+m);
System.out.println("n="+n);
}
}
}
Answers
(1)Answer:
Output:
0
2
4
6
8
Explanation: Here, we have used the for loop that will first initialize the value of the variable i with the value -1. After that it will check the condition if i is less than 10. After it, we will get the output as 0 as we have used a preceding ++ operator with i (++i) and hence its value will increase by 1 before giving the output. Then the for loop will further increase the value of 0 to 1 due to the presence of a succeeding ++ operator in the parenthesis of the for loop (i++) and again, 1 will increase to 2 before showing us the output and hence, we will see the output as 2 in the next line. This will continue till the required condition is met, i.e., i < 10.
(2)Answer:
Output:
60
Explanation: Here, we have first initialized the two variables i and k with the values 2 and 1 respectively. After this we have used a while loop with the condition ++i < 6. Thus, the value of i will increase by 1 before it can be used further because of a preceding ++ operator in the condition. So, the value of i will become 2 then. Now, the while loop will check the condition if 2 is greater than 6. Then it will move forward to the next statement where the value of k will be equal to k * i (as k *= i or k = k * i are the same). So the value of k will become 3 ( as i = 3 and k = 1). This will continue till the required condition (++i < 6) is met. And finally the value of k will become 60 at last and the output will be 60.
(3)Answer:
Output:
m=3
n=14
m=4
n=13
m=5
n=12
m=6
n=11
m=7
n=10
Explanation: Here, firstly we have first initialized the variables m and n with the values 2 and 15 respectively. After this, we have used a for loop and in the for loop we have initialized one more variable i with the value 1 and gave the condition i <= 5. So, it will first check if the value of i is less than or equal to 5 and then it will allow the control to enter the loop. So firstly i =1 and it is less than 5 so it will enter the loop. Then, inside the for loop, the values of m and will increase by 1 and decrease by 1 respectively due to the increment and decrement operators in the statement. So, the values of m and n are now 3 and 14 respectively. So, after that, we will get the output as m=3 and in the next line we will get n=14. This will continue till the required condition (i <= 5) is fulfilled.