Loops Flashcards
Loops in Java
PURPOSE:
Loops in Java are used to execute a block of code repeatedly
Loops will run until a termination condition is met
Loops are helpful to eliminate duplicating codes and time saving
For loop (traditional i loop)
There are 3 steps to follow to create a for loop
The loop must have initialization point
- There should be a termination point (condition) where loop ends
- Change – increment or decrement value
Syntax: for(initialization; termination condition; change){ //code block to be executed }
While loop
While loop executes a block of code depending on a condition
While condition is true, the block of code will be executed
Syntax: while(test condition){ //code block to be executed }
For loop vs While loop
For loop is used to execute a block of code and preferred when we know the exact number of iteration
Syntax:
for(initialization; termination condition; change){
//code block to be executed
}
While loop is used to execute a block of based on a condition and total number of iteration is not certain (dynamic) Syntax: while(test condition){ //code block to be executed }
While loop can be used instead of for loop
Do While loop
This is very similar to while loop
However, it will execute the block of code at least once
It will first execute the block of code, then will check the condition
While condition is true, the block of code will be executed again
Syntax: do{ //code block to be executed } while(test condition);
Loop control statements
break;
break is used to terminate the loop
continue;
continue is used to skip only current iteration if a specified condition occurs, and continues with the next iteration in the loop
Nested loops
Any loop statement can be used in another loop
Executing a loop inside another loop is known as nested loops
The first loop is known as outer loop, and the second one which is used inside the first one is known as inner loop
NOTE: it is used with Arrays and other collections in Java
When do you use the break;
in loops and switch statements
it terminates the block