Rewrite the program using for loop:(3) int i=1; int d=5; do { d=d*2; System.out.println(d); i=i -1 ; } while(i<=5);
Answers
Note:
Firstly, this loop runs for infinite times, as the value of i keeps on decreasing from 1 to 0,-1,-2,... and the condition given is i<=5, for termination.
As the value of i can never satisfy i<=5; iteration keeps running.
I have provided the attachments of the compilation of two codes. Have a look!
Given Code:
public class Something
{
public static void main(String[] args)
{
int i=1;
int d=5;
do
{
d=d*2;
System.out.println(d);
i=i-1 ;
} while(i<=5);
}
}
Output:
10
20
40
80
160
320
640
1280
2560
5120
10240
20480
...
Rewriting the code using for loop:
public class Something
{
public static void main(String[] args)
{
int d=5;
for(int i=1; i<=5; i--)
{
d=d*2;
System.out.println(d);
}
}
}
Output:
10
20
40
80
160
320
640
1280
2560
5120
10240
20480
...
Explanation:
The main difference between do while loop and for loop is; The loop will iterate one time executing the code within, irrespective of the condition in do-while loop. Coming to for loop, the loop iterations take place only if the condition satisfies. If not, the code within doesn't get executed, not even for once.
Hope it helps. If yes, leave a smile. :)