Tag Archives: while loop example

Python: while loop

The while loop is used to execute a piece of code as long as the test condition is true. While loop is preferred whenever the number of iterations is not known.

Syntax

Python while loop

Example

	num=5
	count=1
	while count <= num:
	    print("The current number is:",count)
	    count+=1

Output

The current number is: 1
The current number is: 2
The current number is: 3
The current number is: 4
The current number is: 5

In the above example, while loop will check the condition continuously the value count and compare with num value as long as condition is true. In case of true all the statement inside the while loop will execute.

Java: while loop

The Java while loop is a control flow statement, used to iterate a part of the program several times. It preferred when the number of iteration is not fixed.

See Also: Java: Types of Looping Statements

Syntax:


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

Flow chart for while loop

while loop flow chart

Example: Print even numbers between 1 to 20.

This is the same example written in for loop also in the previous post.

class WhileLoopExample {
public static void main(String[] args) {
   System.out.println("Even Numbers between 1 to 20 :");
   int i=1;
   while(i&lt;=20){
     // If modulus of number after devision 2 is 0 then even number
     if (i % 2 == 0) {
            System.out.println(i);
       }
      i++;
     }
   }
}

Output:


Even Numbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Infinitive While Loop

If you pass true or condition satisfied always as true in the while loop, it will be execute infinitive times.

Syntax:


while(true){  
//code to be executed  
}  

Example: while infinite loop

public class WhileExample2 {
public static void main(String[] args) {
    while(true){
        System.out.println("FacingIssuesOnIT”);
    }
}
}

Output:


FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
.................
..............
............

ctrl+c

Note: Use press ctrl+c to exit from the program otherwise that will continue the print “FacingIssuesOnIT” statement.