OOP IN JAVA - LOOP [ while loop AND for loop ]
LOOPS
Loops can execute a block of code as long as a specified condition is reached and also they are handy because they save time, reduce errors, and they make code more readable.
there are two ways of loop
1. While Loop
2. For Loop
while Loop
The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is recommended to use the while loop. The while
loop loops through a block of code as long as a specified condition is true.
syntax
while (condition) {
// code block to be executed
increment / decrement of statement
}
Example Below :
the code in the loop will run, over & over again, as long as a variable (j) is less than 10:
int j = 4;
while ( j < 10) {
sout (j)
j++;
}
Don't forget to increase the variable used in the condition, otherwise the loop will never end!
For Loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
for loop is can initialize the variable, check condition and increment/decrement value. It consists of four parts:
Initialization: It is the condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.
Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
Statement: The statement of the loop is executed each time until the second condition is false.
Ex - public class School{
public static void main(String[] args) {
for(int c=39; c<=110;c++){
System.out.println(c);
}
}
}
Comments
Post a Comment