1. What are the differences between a while loop and a do-while loop? Convert the following while loop into a do-while loop.
Perbedaan antara perulangan while (while loop) dan perulangan do-while (do-while loop), yaitu:
- Perulangan while (while loop)
Dimana, dalam while loop akan dilakukan cek terlebih dahulu, baru di eksekusi (pre-test-loop). Dalam while loop minimal statement yang di print adalah nol (0).
- Perulangan do-while (do-while loop)
Dimana, dalam do-while loop akan dilakukan eksekusi terlebih dahulu, baru kemudian di cek (post-test-loop). Dalam while loop minimal statement yang di print adalah satu (1).
int i = 1;
do
{
if (i %2 == 0);
System.out.println (i);
}
while (i < 10);
int i = 1;
do
{
if (i %2 == 0);
System.out.println (i++);
}
while (i < 10);
int i = 1;
do
{
if ((i++) %2 == 0);
System.out.println (i);
}
while (i < 10);
2. Do the following two loops result in the same value in sum?
Ya, hasil output dari kedua statement di atas sama.
3. What does the following statement do?
for( ; ; ){
do something;
}
Yang di maksud dengan statement di atas adalah bahwa loop terus melakukan sesuatu tanpa batas (infinite loop) atau biasa juga di sebut dengan statement kosong.
4. Can you always convert a while loop into a for loop? Convert the following while loop into a for loop.
Ya, while loop bisa di convert ke for loop.
Hasil convert dari statement di atas, yaitu:
int sum =0;
for (int i=1; sum < 10000; i++)
{
sum +=i;
}
5. After the continue statement is executed in the following loop, which statement is executed? Show the output.
Hasil output dari statement di atas adalah
1
2
1
2
2
3
( Novianti – 1701298144 )
http://www.binus.ac.id
Leave a Reply