Commonly used looping constructs:

  1. Process a list of N items:

    
          for (i = 0; i < N; i = i+1 )   
          {
             ....Process one item
          }
    
    OR:
    
          for (i = 0; i < N; i++)
          {
             ....Process one item
          }
    
    

    DEMO program - reverse characters in a string: click here

  2. Reading input data until "End of Input" detected

    
          String inputLine;
          boolean done = false;
    
          while ( !done )
          {
             inputLine = console.readLine();      
    	 if ( inputLine == null )
    	 {
                done = true;
    	 }
    	 else
    	 {
                ....Proces inputLine
    	 }
          }
    
    OR:
    
          String inputLine;
    
          while ( ( inputLine = console.readLine() ) != null )    
          {
             ....Proces inputLine
          }
    
    

    Pascal programmers have to settle for the first solution.
    C/C++/Java programmers prefer the second solution....

    DEMO program - read in lines from input and reverse each line: click here

  3. Reading input data until a "sentinel" is detected

    
          String inputLine;
          boolean done = false;
    
          while ( !done )
          {
             inputLine = console.readLine();      
    	 if ( inputLine.equals(sentinel) )
    	 {
                done = true;
    	 }
    	 else
    	 {
                ....Proces inputLine
    	 }
          }
    
    OR:
    
          String inputLine;
    
          while ( ( inputLine = console.readLine() ).equals(sentinel) )    
          {
             ....Proces inputLine
          }
    
    OR:
    
          String inputLine;
    
          while ( true )  // Loop indefinitely ! 
          {
             inputLine = console.readLine();      
    	 if ( inputLine.equals(sentinel) )
    	 {
                break; // Exits loop !!! 
    	 }
    	 
             ....Proces inputLine
          }