• A.razaq

T14- While do..while loop

Updated: Jan 31

in this tutorial we will continue our 2nd type of loop which is the ( while loop ).

so what is while loop ?

while loop is a control flow statement that allows the code to execute repeatedly forever until a certain condition is met



int i = 0;
while (i < 5) {
System.out.println("while Loop Example " + i);
  i++;
  }
 


this is how a while loop syntax would look like, as you can see

this code above means while the ( i ) value is less than 5

execute the code below and print the message until (i) is no longer less than 5.


the increment (i++) will keep adding values every time the code execute until i is not less than 5

----

now when you think of it , while loop and for loop are very similar , actually almost the same

The difference between for loop and while loop is that in ( for loop) the number of iterations to be done is already known and is used to obtain a certain result whereas in (while loop) the command runs until a certain condition is reached and the statement is proved to be false.


so this below

	int i = 0;
		while (i < 5) {
		  System.out.println("while loop example"+i);
		  i++;
	}

is exactly like this


	for ( int i=0; i<5; i++) {
			System.out.println("for loop example "+i);
		}

lets test them both and see the result





now we understood the while loop , lets dissect the other form which is Do..while loop

so again we ask ourselves , what is do while loop?

do while loop is is a variant of the while loop , it execute the code once before even checking if the condition is true or false, so do while loop will make sure the code is executed once whether the condition is true or false and if the condition is true , the loop will continue


syntax of do while loop


do {  
// code to be executed 
}
while (condition);

lets take an example



	int i = 0;
		do {
		  System.out.println("do while example");
		  i++;
		}
		while (i > 5);

now you can see i = o

and the condition is ( i > 5 ) and obviously i is not bigger than 5

but if we run the program



you can see the code is executed, so (do while) will make sure your code is executed at least once whether your condition is met or not


now lets see when the condition is met



	int i = 0;
		do {
		  System.out.println("do while example " + i);
		  i++;
		}
		while (i < 5);

now we made the condition i<5




as you see the loop will execute normally as a while loop


9 views0 comments

Recent Posts

See All