- Hello guys today we are going to learn about loops in java language. There are 4 main types of loops in java language. Those are :
- for loop
- while loop
- do while loop
- for-each loop
- A loop statement allows us to execute a statement or group of statements multiple times.
- let see how the for loops work.
public class Testing {
public static void main(String args[]){
for(initializing; boolean expression; increment or decrement statement){
loop body;
}
}
}
- Now lets try to print 1-100 numbers using java for loop.
public class Testing {
public static void main(String args[]){
for(int i=0;i<100;i++){
System.out.println(i+1);
}
}
}
- lets try to write a code for print the even numbers from 1-100.
public class Testing {
public static void main(String args[]){
for(int i=1;i<100;i++){
if(i%2==0){
System.out.println(i);
}
}
}
}
- Extreme for loop-loop without braces. Only line immediately after for does belongs to for loop.
public class Testing {
public static void main(String args[]){
for(int i=0;i<5;i++)
System.out.println("hello");
System.out.println("end of loop");
}
}
public class Testing {
public static void main(String args[]){
for(int i=0;i<5;i++){
System.out.println("Outer");
for(int j=0;j<;5;j++){
System.out.println("Inner");
}
}
}
}
- while loop-Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
public class Testing {
public static void main(String args[]){
int x=0;
while(x != 10){
System.out.println(x);
x++;
}
}
}
- do-while loop -Like a while statement, except that it tests the condition at the end of the loop body
public class Testing {
public static void main(String args[]){
int x=0;
do{
System.out.println(x);
x++;
}while(x!=10);
}
}