Java: While loop

while loop in java

While  Loop 

Looping is a cardinal feature of any programming language. It allows the execution of a set of instructions  or commands repetitively for a specified number of iteration, until a certain condition is met.

Using loops saves the programmer from the hassle of writing the same code again and again to obtain the desired results. We have three different loops in programming:

  • For Loop.
  • While Loop.
  • Do- While loop.

Understanding the concept

The While loop is a functionality of a programming language that comes into play when some code needs to be executed iteratively until a given condition is true. In other words, the code is repetitively executed based on a given boolean condition. In this type of looping technique the control flow enters the loop only when the boolean condition returns true.

The three steps in while loop can be seen as:

Test: A boolean function which when tested true advances the control flow. It needs to be tested after each iteration.

Statement/Conditional code: Once the condition is satisfied the the body of the code specified by the programmer as per his need is executed.

Increment/Decrement: The code is incremented/decremented in order to bring the condition close to zero or false so that the loop can terminate.

For better understanding, the working of this flowchart has been given in the following image.

While-loop

Syntax of While Loop

 while(condition_check) 
{
    // Conditional code
increment/decrement; }

Now that we have seen the syntax of the while loop, let us understand it further with the help of an example. 

Suppose we want to print a series of prime numbers starting from 0 till 100. Now instead of writing the code again and again we will be using while loop:

Run

public class Main
{

  public static void main (String[]args)
  {
    int i, num = 1, c;

      System.out.println (" Prime Numbers from 1 to 100 are : ");
    while (num <= 100)
      {
	c = 0;
	i = 2;
	while (i <= num / 2)
	  {
	    if (num % i == 0)
	      {
		c++;
	      }
	    i++;
	  }
	if (c == 0 && num != 1)
	  {
	    System.out.print (num + " ");
	  }
	num++;
      }
  }
}

Output:

 Prime Numbers from 1 to 100 are : 
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription