Java Loop
In computer programming, loops are used to repeat a specific block of code until a certain condition is reached.
Java for Loop
Syntaxfor (initialization; testExpression; update)
{
// codes inside for loop's body
}
Example-Print only even number from 2 to 50.
class Loop { public static void main(String[] args) { for (int i = 2; i <= 50; i+=2) { System.out.println(i); } } }
Java nested Loop
When we use loop within loop is called nested loop. That means placing of one loop inside the body of another loop is called nesting.
Example-Print multy table from 2 to 5.
public class Multitbl { public static void main(String[] argv) { int a,b,c; for(a=2;a<=5;a++) { for(b=1;b<=10;b++) { c=a*b; System.out.println(a+" x "+b+" = "+c); } } } }
Output
Example-Print pattern.
public class Mypattern { public static void main(String[] argv) { int a,b,c; for(a=1;a<=5;a++) { for(b=1;b<=5-a;b++) { System.out.print(' '); } for(c=1;c<=2*a-1;c++) { System.out.print(c); } System.out.println("\n"); } } }
Output
Java While Loop
The while loop rotates through a block of code as long as a specified condition is true.
Syntaxwhile (condition) {
Example- Enter any digited number then check and print number is even digited or odd digited along with reverse value.
// code block to be executed
}
import java.io.*; import java.util.*; public class Myno1 { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("Enter any digit"); int b=0,c=0,d=0,r=0; int a=input.nextInt(); while(a!=0) { b=a/10; d=a-b*10; r=r*10+d; c++; a=b; } if(c%2==0) { System.out.println("Even digit and Reverse="+r); } else { System.out.println("Odd digit and Reverse="+r); } } }
Output
Java Break
The break statement can also be used to jump out of a loop.
Example
class MyClass { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 4) { { break; } System.out.println(i); } } }
Output
0
1
2
3
Java Continue
The continue statement breaks one iteration, if a specified condition occurs, and continues with the next iteration in the loop.
Example
class MyClass { public static void main(String[] args) { for (int i = 0; i < 6; i++) { if (i == 4) { { continue; } System.out.println(i); } } }
Output
0
1
2
3
5
6
This example skips the value of 4:
0 Comments