looping statements in java with examples
introduction looping statements in java:
In programming languages, loops are used to perform a set of commands / tasks over and over again when certain conditions are true. There are three types of loops in Java.
Skipping programming languages is a feature that makes it easy to execute a set of commands / tasks over and over again while the situation is simplified.
Java offers three ways to create traps. While all methods offer the same basic functionality, they differ in their syntax testing time and status
What are the looping statements in Java?
Java provides three repetition statements/looping statements that enable programmers to control the flow of execution by repetitively performing a set of statements as long as the continuation condition remains true. These three looping statements are called for, while, and do… while statements.
Types of looping statements in java:
1.while loop java:
A loop while a control flow statement that allows code to be repeated multiple times depending on a given Boolean status. The time loop can be thought of as a recurring statement.
Syntax :
while (boolean condition)
{
loop statements...
}
Example while loop java:
// Java program to illustrate while loop
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;
// Exit when x becomes greater than 4
while (x <= 4)
{
System.out.println("Value of x:" + x);
// Increment the value of x for
// next iteration
x++;
}
}
}
2.for loop in java:
for loop provides a shortcut to loop the loop structure. Unlike a temporary loop, the statement uses a start, position and up / down line in one line thus providing a short, easy to correct breakout error.
Syntax:
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
Example for loop in java:
// Java program to illustrate for loop.
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}
3.Nested For Loop in java:
If we have a loop inside another loop, it is known as nested for loop. The inner loop works perfectly when the outer loop is removed.
Example Nested For Loop in java:
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
No comments:
Post a Comment