Wednesday 5 February 2014

Branching statement: continue

continue statement skips the current iteration of a for, while, do-while loops. Just like break, continue also has two forms.
    1. unlabelled continue
    2. labelled continue

Unlabelled continue
    Syntax
        continue;

Example: Count the number of odd values from 0 to 10
class ContinueEx{
 public static void main(String args[]){
  int counter = 0;
  
  for(int i=0; i < 11; i++){
   if(i % 2 == 0)
    continue;
   System.out.println(i);
   counter++;
  }
  
  System.out.println("Total number of odd numbers from 0 to 10 is " + counter);
 }
}
       
Output
1
3 
5
7
9  
Total number of odd numbers from 0 to 10 is 5 
       
Labelled continue
     Syntax
     continue labelName;

Example
class ContinueEx{
 public static void main(String args[]){
  int counter = 0;
  
  myLabel:
   for(int i=0; i < 11; i++){
    if( i < 10)
     continue myLabel;
    System.out.println(i);
   }
   
  System.out.println("I am out of the label");
 }
}

Output
10
I am out of the label

break statement                                                 arrays                                                 Home

No comments:

Post a Comment