Loops - Part 1

What do we use a "loop" for?











What the three types of loops in Java?

1.


2.


3.


How would we add up the numbers from 1 - 10 by hand?

















for loops

for (initialization part;   condition;   increment/decrement part) {

loop body

}





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



  }

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




















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


















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

  









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

  









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

  









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



What is the scope of the "loop variable"? What if we want to use it outside the loop?

  //Use a for loop to add up the numbers from 1 - 10
  
  final int MAX = 10; 
  int sum = 0;
  for ( int i = 1; i <= MAX; i++ ) {
   
   sum += i;
  
  }
 
  System.out.println("i = " + i);
  
  System.out.println("sum = " + sum);
  

    

  








  //ADVANCED: A loop without a "body" and without an 
  //          "initialization part" 
  //          that finds the smallest multiple of 7 greater than 100 
  
  final int MAX = 100; 
  int i = 0;
  for ( ; i <= MAX; i += 7 );
   
  System.out.println("i = " + i);