Give an example of a while loop, then provide the equivalent do-while loop and for loop. Then give a different example of a do-while loop, along with the equivalent while loop and for loop. Finally, give an example of a for loop, along with the equivalent while loop and do-while loop. Use your examples to illustrate the advantages and disadvantages of each looping structure, and describe those advantages and disadvantages.
1.
public class Main
{
public static void main(String[] args) {
//while loop
System.out.println("while loop");
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
//do while loop
System.out.println("do while loop");
int j = 0;
do {
System.out.println(j);
j++;
}
while (j < 5);
//for loop
System.out.println("for loop");
for(int n=0;n<5;n++){
System.out.println(n);
}
}
}
2.
public class Main
{
public static void main(String[] args) {
int m =5;
//do while loop
System.out.println("do while loop");
int j = 0;
do {
System.out.println(j*m);
j++;
}
while (j < 5);
//while loop
System.out.println("while loop");
int i = 0;
while (i < 5) {
System.out.println(i*m);
i++;
}
//for loop
System.out.println("for loop");
for(int n=0;n<5;n++){
System.out.println(n*m);
}
}
}
3.
public class Main
{
public static void main(String[] args) {
int m =100;
//for loop
System.out.println("for loop");
for(int n=0;n<5;n++){
System.out.println(n*m);
}
//while loop
System.out.println("while loop");
int i = 0;
while (i < 5) {
System.out.println(i*m);
i++;
}
//do while loop
System.out.println("do while loop");
int j = 0;
do {
System.out.println(j*m);
j++;
}
while (j < 5);
}
}
Comments
Leave a comment