// int i=0;
// while(i<5){
// System.out.println(i);
// System.out.println("Java is great.");
// if (i==2){
// System.out.println("Ending the Loop.");
// break;
//
// }
// i ; //DOUBT:WHEN I WRITE i AFTER 4TH LINE WHY "2" IS NOT PRINTED IN OUTPUT.
// }
// int i=0;
// do{
// System.out.println(i);
// System.out.println("Java is Great.");
// if (i==2){
// System.out.println("Ending the Loop.");
// break;
// }
// i ;
// } while (i<5);
// for (int i=0; i<50; i ){
// if (i==2){
// System.out.println("Ending the Loop");
// continue;
// }
// System.out.println(i);
// System.out.println("Java is Great.");
// }
int i=0;
do{
i ;
if(i==2){
System.out.println("Ending the loop.");
continue;
}
System.out.println(i);
System.out.println("Java is Great.");
}while(i<5);
//DOUBT:WHY 5 IS GETTING PRINTED IN THIS EVEN IF THE CONDITION IS (i<5).
Basically in all these codes my doubt is how can i decide the exact posiiton of certain codes to get the appropriate results. Like when i write i ; above the if statement and after the if statement then different results gets printed.
CodePudding user response:
I understand what are you trying to ask.
Like when i write i ; above the if statement and after the if statement then different results gets printed
This is because when you add i after the if statement.
First time if will be skipped because i = 0
, then comes i
, second time it will be skipped as well because i = 1
, then comes i
again. Now i = 2
and you enter if statement. In if statement you have continue
which means "skip rest of the loop and start next cycle". In next cycles i will be 2 forever because you are not reaching part of the code that increments it. So either add i
in if statement, before continue
or keep i
at start as you have in example.
EDIT: If you wanna 4 to be last number printed then use while()
loop instead of do-while()
because in do-while()
you always increment first and evaluate later.
CodePudding user response:
I am afraid the code is correct.
do{
i ;
if(i==2){
System.out.println("Ending the loop.");
continue;
}
System.out.println(i);
System.out.println("Java is Great.");
}while(i<5);
As far as this code is concerned, when 4<5
condition is true code executes the do block and increments the variable i and then prints it, thus the value 5.
I suggest you use the while condition and read about it.