Loops
- In programming language, loops are used to execute a set of instruction or functions repeatedly when some conditions become true.
- Loops can execute a block of code as long as specified condition is reached.
- Loops are handy because they save time, reduce errors, and they make code more readable.
There
are three types of loops in Java.
1. while loop
2. do-while loop
3. for loop
Java While Loop
Syntax:
//code to be executed
}
Here, key point of the while loop is that the loop might
not ever run. When the condition is tested and the result is false, the loop
body will be skipped and the first
statement after the while loop will be executed.
int i = 0;
while (i < 5) {
system.out.println(i);
i++;
}
Note: Do not forget to
increase the variable used in the condition, otherwise the loop will never
end!!
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Output:
2
3
4
5
6
7
8
9
10
Java Infinitive While Loop
If you pass true in the
while loop, it will be infinitive while loop.
Syntax:
//code to be executed
}
Example:
public static void main(String[] args) {
while(true){
System.out.println("infinitive
}
}
}
Output:
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c
Now, you need to press ctrl+c to exit from the
program.
The do-while Loop
The do-while
loop is a variant of the while
loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.
Syntax
do
{
// code block to be executed
}
while
(condition);
The
example below uses a do/while
loop.
The loop will always be executed at least once, even if the condition is false,
because the code block is executed before the condition is tested:
Example
int i
=
0;
do
{
System.out
.println(i
);
i
++;
}
while
(i
<
5);
Do not forget to increase the variable used in the condition,
otherwise the loop will never end!
No comments:
Post a Comment