In this tutorial, we will learn about Looping Statements in Java. Looping Statements helps us to run a piece of code several times. Suppose you want to increment the value of a variable 100 times it means you have to write increment operator with that variable 100 times. Which would just increase workload. but with the help loop, you can increment the value of that variable just by writing it once. We have three types of loops available in java.
- for loop
- while loop
- do while loop
for loop: – for is very easy looping statement. There are a total of three expressions in for loop. First one is an initialization, the Second one is condition and the last one is increment or decrements of a variable. You can see given Syntax of for loop to understand it wisely.
for(initialization ; condition ; inc/dec)
{
//body of loop
}
To understand the flow of for loop you can check out the following flow chart:
class forLoop{
public static void main(String args[])
{
for(int i=0 ; i <10 ; i++)
{
System.out.println("Value of i= "+i);
}
}
}
while loop: – While loop takes a single expression and it allows to execute code multiple time until the condition goes wrong. To understand it more clearly Let’s check out the syntax of while loop.
while(condition)
{
//body of loop
}
To understand flow of the while loop. Please check out the following flow chart diagram.
class whileLoop{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println("Value of i= "+i);
i++;
}
}
}
do-while loop: – The do-while loop is almost similar to while loop except for one difference. do-while loop will run at least once even in the wrong condition Let’s check the syntax of the do-while loop then we will check one example of while loop.
do{
//body of loop
}
while(condition);
Here you can see we write the body of the loop in do block then we write a condition in while at the end of do the block.
To understand the flow of the do-while loop. Please check out the following flow chart diagram.
class whileLoop{
public static void main(String args[])
{
int i=1;
do{
System.out.println("Value of i= "+i);
i++;
}while(i<=10);
}
}