Loop can execute until they reached at specified condition
For Loop
when we know how many times iteration required for the program we use for loop. For example we want to print a numbers from 1 to 10 in this condition we need ten iteration so for loop is better solution.
In for loop "for" is a keyword which contain three parts initialize , terminate and increment.
Syntax:
for(initialize ; terminate ; increment){ //Block of code } for(int i=0 ; i< 10 ; i++){ }
Example
int i = 0; for(i=0 ; i< 10 ; i++){ System.out.println(i); }
For each loop
For manipulating arrays we use for each loop
Syntax:
for (type variableName : arrayName) { // code block to be executed }
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println(i); }
While Loop
While and do while loop uses when we are not confirmed how many iteration needed
Syntax:
while(condition){ //Block of code }
Example
int i = 0; while(i<9){ System.out.println(i); i = i+1; }
Do-While
Syntax:
do{
// Block of code
}(condition)
Example
Scanner obj = new Scanner(System.in); char cont; int i =0; do{ System.out.println(i); i++; System.out.println("If you want to continue press y"); cont= obj.next().charAt(0); }while(cont == 'y' || cont == 'Y' );
0 Comments