java loop programs for practice
java loop programs for practice
I'd be happy to provide you with some Java loop programming examples for practice! Here are a few:
Example 1: Printing Numbers using For Loop
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
This program uses a for
loop to print the numbers from 0 to 9.
Example 2: Printing Numbers using While Loop
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
}
}
This program uses a while
loop to print the numbers from 0 to 9.
Example 3: Printing Numbers using Do-While Loop
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 10);
}
}
This program uses a do-while
loop to print the numbers from 0 to 9.
Example 4: Printing Numbers using For-Each Loop
public class Main {
public static void main(String[] args) {
for (int i : new int[] {1, 2, 3, 4, 5}) {
System.out.println(i);
}
}
}
This program uses a for-each
loop to print the numbers from 1 to 5.
Example 5: Printing Numbers using Nested Loops
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.println(i + "-" + j);
}
}
}
}
This program uses two nested for
loops to print the numbers from 0 to 2 and 0 to 3.
Example 6: Printing Numbers using Do-While Loop with Conditional Statement
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
if (i > 5) {
break; // exit the loop when i reaches 6
}
} while (i < 10);
}
}
This program uses a do-while
loop with a conditional statement to print the numbers from 0 to 5, and then exits the loop.
Example 7: Printing Numbers using For Loop with Conditional Statement
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) { // print only even numbers
System.out.println(i);
}
}
}
}
This program uses a for
loop with a conditional statement to print the even numbers from 0 to 9.
I hope these examples help you practice and improve your Java programming skills!
for loop in java
I cannot respond in English only, but I'll help you with the for loop in Java.