This tutorial is explain about definition of Looping Statement and also explain of for loop, do..while loop, while loop and for each loop with explanation and given example of Java Programming.
Looping Statement in Java: whenever you have statement that is repeated several time then we using loop.
In Java we using four type of looping:-
- for loop
- while loop
- do while loop
- for each loop
1. 1. For loop :- for loop is most commonly used loop. In this looping you initialization, condition and increment/ decrement in a single line.
Syntax:- for(initialization; condition; incr/decr){
// loop body
}
Example:-
class ForLoopExample{
public static void main(String [] args){
for(int i=1; i<=10; i++){
System.out.println("\n" +i);
}
}
}
Output:-
1
2
3
4
5
6
7
8
9
10
2. while loop:- while loop use when we don't know how many times statement execute. Its called a pre test loop. Its also known as entry control loop.
Syntax:- while(condition){
// loop body
}
Example:-
class WhileLoopExample{
public static void main(String [] args){
int i=1;
while(i<=10){
System.out.println("\n" +i);
++n;
}
}
}
Output:-
1
2
3
4
5
6
7
8
9
10
3. do while:- This loop is used when you want to loop execute at leat one time even condition is false. Its called a exit control loop.
Syntax:-
do{
// this body execute at least once
}while(condition);
Example:-
class DoWhileExample{
public static void main(String [] args){
int i=1;
do{
System.out.println("\n" +i);
++n;
} while(i<=10);
}
}
Output:-
1
2
3
4
5
6
7
8
9
10
4. for each:- This loop is used when fatch a value from the collaction of the array.
Syntax:- for(datatype var1: array variable)
{
// statment
}
class ForEachExample{
public static void main(String [] args){
Strining a [] ={"Apple", "Mango", "Grapes", "Banana", "Litchi"};
for(String b : a){
System.out.println(i+ " ");
}
}
}
Output:- Apple Mengo Grapes Banana Litchi
Print * like as Pyramid in Java :-
public class Pyramid {
public static void main(String[] args){
int n = 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
System.out.print(" ");
}
for (int k = 0; k < 2 * i + 1; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
Output:
*
***
*****
*******
*********
0 Comments
Hello Friends, Please comment and share and do not write spam messages