Java Loop Statements

Java Loop Statements, Java Control Flow, Java for loop, while loop, do while loop, enhanced for loop, and Java nested loop statements.

Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true.

Loop Statements in Java

We have four loop structures in Java,

1. for loop
2. while loop
3. do while loop
4. enhanced for loop

1. for loop

Description: It repeats a block of statements for a specified number of times

Syntax:

for (Initialization/Start Value; Condition/End Value; Increment or Decrement){
statements
.
.
}

Example 1: Print 1 to 10 Numbers

for (int i=1; i<=10; i++) {
System.out.println(i);
}

Example 2: Print even numbers up to 20

for (int i=2; i<=20; i+=2) {
System.out.println(i);
}

Example 3: Print 1 to 5 Numbers except 4th Number

for (int i=1; i<=5; i++) {
if (i!=4) {
System.out.println(i);
}
}

Example 4: Print 1 to 10 in reverse order except 4th and 7th Orders

for (int i=10; i>=1; i–) {
if ((i!=4)&&(i!=7)) {
System.out.println(i);
}
}

2. while loop

Description: It repeats a block of statements while the condition is true

Syntax:

Initialization;
while (condition){
statements
.
.
increment/decrement;
}

Example 1: Print 1 to 10 Numbers…

int i=1;

while (i<=10){
System.out.println(i);
i++;
}

Example 2: Print 1 to 5 Numbers except 4th Number

while (i<=5){
if (i!=4){
System.out.println(i);
}
i++;
}

Example 3: Print 1 to 10 Numbers in reverse Order

int i=10;

while (i>=1){
System.out.println(i);
i–;
}

Example 4: Print 1 to 10 Numbers in reverse Order except 4th and 9th numbers

int i=10;

while (i>=1){
if ((i!=4) && (i!=9)){
System.out.println(i);
}
i–-;
}

3. do while loop

Description: It repeats a block of statements while the condition is true and it executes statements at least once irrespective of the condition

Syntax:

Initialization;
do
{
Statements
.
.
Increment/Decrement;
} while (condition);

Example 1: Print 1 to 10 Numbers…

int i=1;

do
{
System.out.println(i);
i++;
} while(i<=10);

Example 2:

int i=20;

do
{
System.out.println(i);
i++;
} while(i<=10);

Example 3: Print 1 to 10 Numbers in reverse order

int i=10;

do
{
System.out.println(i);
i–;
} while(i>=1);

Example 4: Print 1 to 5 Numbers except 3rd Number

do
{
if (i!=3){
System.out.println(i);
}
i++;
} while(i<=5);

4. Enhanced for loop

It executes all elements in an Array

Syntax:

Array Declaration;
for (declaration: Expression/Array){
Statements
.
.
}

Example 1:

String [] languages={“COBOL”, “C”, “Java”, “VBScript”};

for (String lang: languages){
System.out.println(lang);

Example 2:

public static void main(String[] args) {
int a=10, b=5;
int [] mathOperations = new int[3];

mathOperations[0]= a+b;
mathOperations[1]= a-b;

for (int operation: mathOperations){
System.out.println(operation);
}


Java Language Syllabus

Java Videos

Follow me on social media:

2 thoughts on “Java Loop Statements”

Comments are closed.