Loops in Java. In English
LOOPS
Programming languages provide a feature called looping that makes it easier to execute a collection of instructions or functions repeatedly while a condition is true. There are three ways to run the loops in Java. Although the core functionality offered by each method is comparable, there are differences in terms of syntax and condition checking time.
While loop
A control flow statement called a while loop enables code to be repeatedly run in response to a specified Boolean condition. You can think of the while loop as an iterative if statement.
syntax: -
while (boolean condition) { loop statements... }
Example: -
- import java.io.*;
- class Example {
- public static void main (String[] args) {
- int i=0;
- while (i<=10)
- {
- System.out.println(i);
- i++;
- }
- }}
Output - 0 1 2 3 4 5 6 7 8 9 10
Do-while loop
The sole distinction between the do while loop and the while loop is that the do while loop is an example of an exit control loop since it checks for conditions after executing the statements.
The sole distinction between the do while loop and the while loop is that the do while loop is an example of an exit control loop since it checks for conditions after executing the statements.
Syntax: -
do { statements.. } while (condition);
- import java.io.*;
- class Example {
- public static void main (String[] args) {
- int i=0;
- do
- {
- System.out.println(i);
- i++;
- } while (i<=10) }}
Output - 0 1 2 3 4 5 6 7 8 9 10
For loop
The loop structure can be written succinctly using the for loop. A for statement, in contrast to a while loop, combines the initialization, condition, and increment/decrement into a single line, making the looping structure shorter and simpler to debug.
Syntax: -
for (statement1; statement2; statement3;)
{
//body
}
Example: -
- import java.io.*;
- class Example {
- public static void main (String[] args) {
- for (int i=0; i<=10; i++)
- {
- System.out.println(i)
- }
- }}
output - 0 1 2 3 4 5 6 7 8 9 10
Nested for loop
A loop statement inside another loop statement is referred to as a nested loop.
Example: -
- import java.io.*;
- class Example {
- public static void main (String[] args) {
- for(int i = 0; i < 3; i++){
- for(int j = 0; j < 2; j++){
- System.out.println(i);
- }
- System.out.println();
- }
- }}
Output - 0
0
1
1
2
2
For-each loop
Java's for-each loop is used to iterate across arrays and collections. Because we don't need to increase the value or utilize subscript notation, it is simpler to use than a basic for loop.
Instead of using an index, it operates based on elements. It gives back each element in the defined variable one at a time.
Syntax: -
for (variable: array) {
//body
}
Example: -
- import java.io.*;
- public class Example {
- public static void main(String[] args) {
- int arr[]={11,12,13,14,15};
- for(int i:arr){
- System.out.println(i);
- }
- }}
Output - 11
12
13
14
15
Comments
Post a Comment