Loops_in_java
Loops_in_java
Repetition statements are essential to control flow structures in Java. They allow you to
execute a block of code multiple times, either based on a specific condition or a
predetermined number of iterations
There are 3 types of loops in java
1) for loop
2) while loop
3) do while loop
1) for loop
Java for loop is a control flow statement that allows code to be executed repeatedly
based on a given condition. The for loop in Java provides an efficient way to iterate over a
range of values, execute code multiple times, or traverse arrays and collections.
Syntax
for (initialization; condition; update)
{
//Code to execute
}
Example
}
Explanation:
{
System.out.println(i);
}
3)
int sum = 0;
}
System.out.println(x);
5)
int countEven = 0;
int countOdd = 0;
for (int i = 1; i <= 5; i++)
{
if (i % 2 == 0)
{
countEven++;
}
else
{
countOdd++;
}
}
System.out.println("Even count: " + countEven);
System.out.println("Odd count: " + countOdd);
2) WHILE LOOP
Java while loop is a control flow statement used to execute the block of
statements repeatedly until the given condition evaluates to false. Once the
condition becomes false, the line immediately after the loop in the program is
executed.
while (test_expression)
{
// statements
update_expression;
}
2)
int i = 1;
while (i <= 9)
if (i % 2 != 0)
System.out.println(i);
i++;
}
Final Output
13579
4)
int count = 0;
count++;
Do while
Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while
check for the condition after executing the statements of the loop body for once
do
{
Update_expression
}
while (test_expression);
1)
int i = 1;
do {
System.out.println(i);
i++;
2)
int count = 1;
do {
System.out.println("Hello");
count++;
do {
if (num % 2 == 0) {
break;
num++;