Java loop

Loops

Loops: Repeats a statement or group of statements while a given condition is true.
It tests the condition before executing the loop body.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the “for loop” because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination;
increment)
{
statement(s)
}

The program, ForLoop, uses the general form of the for statement to print the numbers 1 through 10 to standard output.

class ForLoop
{
public static void main(String[] args){
for(int i=1; i<6; i++) { System.out.println("Count is: " + i); } } }

output::
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Enhanced For Loop Program

class EnhancedForLoop
{
public static void main(String[] args)
{
int[] numbers = {1,2,3,4,5};
for (int item : numbers)
{
System.out.println(“Count is: ” + item);
}
}
}

In this example, the variable item holds the current value from the numbers array.
output::
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.

while(Boolean_expression)
{
// Statements
}

While Loop Program

public class Wloop {
public static void main(String args[])
{
int x = 10;
while( x < 16 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } }

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
do-while loop
do-while loop is similar to while loop, however there is a single difference between these two.
Unlike while loop, do-while guarantees at-least one execution of block of statements.
do-while loop program

do
{
statement(s) //block of statements
}
while (Boolean expression);
class DoWhileLoopExample {
public static void main(String args[])
{
int i=10;
do
{
System.out.println(i);
i–;
}
while(i>1);
}
}

output::
10
9
8
7
6
5
4
3
2
day is variable if the value of the day variable is 1 ,then it will print monday ,if 2 then tuesday so on…..

BACK

NEXT