While loop in Java

While loop in Java

Loops are used to repeat some steps until the desired condition is satisfied. Loops basically execute certain piece of code which programmer does not want to write again and again. For e.g. if I want print numbers from 1 to 100, I have to declare 100 variables assign values to them and print them. It will definitely make my program large and will consume a lot of memory. Thus to avoid this problems looping structure provides easiest way by re-executing everything written inside it. While loop in Java comes under branching looping structure. Syntax-

while(condition)
{
  ...
  ...
}

Q. Write a program to print 1-10 numbers using while loop in java.

Code-

class numbers
{
  public static void main(String[] args) {
    int i=1;
    while(i<=10)
    {
	System.out.println(i);
	i++;
    }
  }
}

Output-

while loop output

Explanation-

First we declare the variable ‘i’ with value 1. Then condition is checked and code inside it is executed. If value of ‘i’ is less than or equal to 10 then while loop is executed. Inside while loop ‘i’ is printed and then incremented. This continues till the value of ‘i’ equals 10. When it become 11 the condition becomes false and the control of program gets outside the while loop.

Program parts-

  1. class– Used to declare a class in java.
  2. public– Access modifier which represents it is visible to all.
  3. static– The main method is declared as static, so it doesn’t require to create an object to invoke the main method.
  4. void– Return type of the method.
  5. main– Represents the starting point of the program.
  6. String[] args– Used for command line argument.
  7. System.out.println()– System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. System.out.println is used to print a statement.

Conclusion-

So this is the concept of while loop in Java. We hope it was clear to you. If you have any doubts tell us in the comment section. For daily updates and more such content do follow us on Instagram.

Keep programming!

ErrorFreeProgram.

2 COMMENTS

Leave a Reply

Your email address will not be published. Required fields are marked *