Loop Structure
It is aslo known as repetitive structure. Loop structure is used to run the block of codes until the condition is satisfied. While in execution, the if the condition is true then it is executed if the condition is false then the loop is terminated and follows the next statement of loop. Loop structure continue to execute until the condition is satisfied and it is very useful in many areas because of this feature.
In java programming language, there are three options to use repetitive structure.
1) 'while' statement
2)'do-while' statement
3)'for' statement
1)'while' statement
In while statement, certain code of block runs which is inside the while loop structure until the condition becomes false. After being the condition false, the loop will terminate itself. Syntax:-
while(<condition expression>)
{
//program code
}
2)'do-while' statement
It is also a type of statement. In this type of structure, while expression is used at the last of the loop structure. In While loop, at first the condition is checked and if the condition is true then it runs the block of code. in do-while loop, at first the statement is run and then check the condition. Note that at the end of while expression ' ; ' must be used.Syntax:-
do{
//program code
}while(condidion);
3)'for' statement
This structure helps us to run the certain block of code for a fix number of time. We can say that, it is just like saying 'repeat the condition for 50 times or 100, as required per your need'. Syntax:-
for(int i=0;i<10;i++){
System.out.prinltn("number"+i);
}
The break statement
We used break statement is the switch case.The break statement is used to terminate the loop in execution of the code. Syntax:-
public class BreakDemo
{
public static void(String args[])
{
int a=1;
while(a<10)
{
System.out.println("number"+a);
if(a==10)
break;
a++;
}
}
}
The continue statement
The continue statement skips the current step of iteration of a for, while, or do-while loop. It however does not break out from the loop block, but instead returning to the point where the termination condition expression is evaluated. Figure 3.16 demonstrates the use of continue statement. The programme prints even number because whenever a % 2 != 0, i.e. odd number, the continue statement is executed and the code skip the rest of the code after the continue statement. Flow is returned to the beginning of the for loop. Syntax:-
public class ContinueDemo
{
public static void main(String arg[]){
int a;
for(a=0;a<11;a++)
{
if(a %2!=0)
continue;
System.out.println("number"+a);
}
}
Comments
Post a Comment