Loops - Part 2

while loops

initialization part;

while  (   condition  )  {

     loop body

     increment/decrement part

}

  //Use a while loop to add up the numbers from 1 - 10
  
  final int MAX = 10; 
  int sum = 0;
  
    
  while (                                     ) {
   
 


  }
  System.out.println("sum = " + sum);
FLOWCHART:


















  //Use a while loop to output the numbers from 10 - 1
  
  final int MAX = 10; 
  
  
  while (                      ) {
   
    
    
  
  
  
  }







  //Use a while loop to output the numbers from 0 - 100 
  //counting by 5's
  
  final int MAX = 100; 
  
  
  while (                                              ) {
   


    
    
  }

















  //What does this while loop do?
  
  final int MAX = 10; 
  
  int i = 15;
  
  while ( i <= MAX ) {
   
    System.out.println(i);
    
    i++;
  }







  //What does this while loop do?
  
  final int MAX = 1024; 
  
  int i = 1;
  
  while ( i <= MAX ) {
   
    System.out.println(i);   
    
    i *= 2;
  }

  



  //What does this while loop do?
  
  final int MAX = 1024; 
  
  int i = 1;
  while ( i <= MAX ); {
   
    System.out.println(i);   
    
    i *= 2;
  }

do while loops

initialization part;

do    {

     loop body

     increment/decrement part

}

while  (   condition  )  ;

  //Use a do while loop to add up the numbers from 1 - 10
  
  final int MAX = 10; 
  int sum = 0;
  
    
  do {
   
 


  } while (                                     );
  
  System.out.println("sum = " + sum);
FLOWCHART:














  //Use a do while loop to output the numbers from 10 - 1
  
  final int MAX = 10; 
  
  
  do {
   
    
    
  
  
  
  } while (                      );


  //Use a do while loop to output the numbers from 0 - 100 
  //counting by 5's
  
  final int MAX = 100; 
  
  
  do  {
   


    
    
  } while (                                              );


  //What does this do while loop do?
  
  final int MAX = 10; 
  
  int i = 15;
  
  do {
   
    System.out.println(i);
    
    i++;
    
  }  while ( i <= MAX );



Nested Loops

We can use "nested loops" to print out these patterns:





                  i (rows)       j (stars)

*
**
***
****
*****


final int ROWS = 5;

for (                                     ) {

  for (                                   ) {
  
    
    
  }
  
 
 
 
}







               i (rows)  j(spaces)  j(stars)        

    *
   **
  ***
 ****
*****


final int ROWS = 5;

for (                                     ) {

  for (                                   ) {




  }
  
  for (                                   ) {





  }
  
 
 
 
 
}