Loops In Java
In Java, there may be requirement of the situation that you wants to execute a piece of code number of times, In that case loops may help you to handle the situation and run code multiple times.
Types of loop in java:-
- do...while loopLike a while statement, except that it tests the condition at the end of the loop body.
2. while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
3. for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Example do..while Loop:
public class Loops {
public static void main(String[] args) {
do {
System.out.println(a);
a++;
}while(a<10);
}
}
Example while Loop:
public class Loops {
public static void main(String[] args) {
int a = 10;
while(a>0) {
System.out.println(a);
a--;
}
}
}
Example for Loop:
public class Loops {
public static void main(String[] args) {
for(int a=10; a>0; a--) {
System.out.println(a);
}
}
}
0 comments:
Post a Comment