Loops

Chapter 5

Code Repo

What is loop?


Condition that cause a block of code to repeat.

Opening Problem



						Problem: Print welcome to java 100 times

                        System.out.println("Welcome to Java!");
                        System.out.println("Welcome to Java!");
                        System.out.println("Welcome to Java!");
                        System.out.println("Welcome to Java!");
                        System.out.println("Welcome to Java!");
                        System.out.println("Welcome to Java!");
                        
                        … 
                        … 
                        … 
                        System.out.println("Welcome to Java!");
                        System.out.println("Welcome to Java!");
                        System.out.println("Welcome to Java!");
                        

					

Solution


						Problem: Print welcome to java 100 times using loop
                        
                        int count = 0;
                        while (count < 100) {
                          System.out.println("Welcome to Java");
                          count++;
                        }
                        
                        

					

The while Statement


  • If the condition is true, the statement is executed
  • Then the condition is evaluated again, and if it is still true, the statement is executed again
  • The statement isexecuted repeatedly until the condition becomes false

						while (loop-continuation-condition) {
                            // loop-body;
                            Statement(s);
                          }
                          
                       
                          int count = 0;
                          while (count < 100) {
                            System.out.println("Welcome to Java!");
                            count++;
                          }
                          

					

Trace While Loop


						int count = 0; //Initialize count
                        while (count < 2) {
                        System.out.println("Welcome to Java!");
                        count++;
                    }
                //Demo on Intellij
                  
					

Problem


                            int i = 1;
                            .......
                            (i < 6) {
                            System.out.println(i);
                            
                            ......
                            }
                      
                        

Solution


                            int i = 1;
                            while
                            (i < 6) {
                            System.out.println(i);
                            i++;
                            }
                      
                        

Ending a Loop with a Sentinel Value


  • Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value.

                        The data != 0 within the while (data != 0) { ... } 
                        is the sentinel-controlled-condition.
                  
                    

Sentinel Value

Caution


Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1:


						double item = 1; double sum = 0;
                        while (item != 0) { // No guarantee item will be 0
                        sum += item;
                        item -= 0.1;
                        }
                        System.out.println(sum);

					

Do- While Loop


                            do {
                                // Loop body;
                                Statement(s);
                              } while (loop-continuation-condition);
         
                        

The do Statement


  • The statement is executed once initially, and then the condition is evaluated
  • The statement is executed repeatedly until the condition becomes false
  • The body of a do loop executes at least once

                        int count = 0;
                        do
                        {
                        count++;
                        System.out.println (count);
                        } while (count < 5);
                        

Problem


                            int i = 1;
                            
                             {
                              System.out.println(i);
                              i++;
                            }
                            
                             (i < 6);
                      
                        

Solution


                            int i = 1;
                            do
                             {
                              System.out.println(i);
                              i++;
                            }
                            while
                             (i < 6);
                        

for Loops

  • The initial-action in a for loop can be a list of zero or more comma-separated expressions.
  • The initialization is executed once before the loop begins
  • The statement is executed until the condition becomes false
  • The increment portion is executed at the end of each iteration

                          

                            for (initial-action; loop-continuation-condition; action-after-each-iteration) {
                                // loop body;
                                Statement(s);
                             }
                            for (int i = 0, i<100; i++) {
                              // Do something
                            }  
                             
                    

                           
                             
                             int i;
                             for (i = 0; i < 100; i++) {	 
                               System.out.println("Welcome to Java!"); 
                             }
                             
                    

Problem


                            

                            (int i = 0; i < 10;  ) {
                              System.out.println("IS 147");
                            }
                      
                        

Solution


                           
                            for(int i = 0; i < 10; i++) {
                            System.out.println("IS 147" );
                            }
                        

Note

  • The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements.
  • The following two for loops are correct. They are rarely used in practice.

                        for (int i = 1; i < 100; System.out.println(i++));

                         for (int i = 0, j = 0; (i + j < 10); i++, j++) {
                            // Do something
                          }     
                          
                        
                              
                        

While / Do while/ For Loop


                //using while loop
				 int count = 0; //Initialize count
                  while (count < 5) {
                  System.out.println("Welcome to Java!");
                  count++;
              }

                //using do while loop
                 int count1 = 0;
                 do
                {
                  count1++;
                 System.out.println ("Welcome to Java!");
               } while (count1 < 5);
     // Using For loop
               int i;
               for (i = 0; i < 5; i++) {	 
                System.out.println("Welcome to Java!"); 
             }

                    

Note

  • If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion:
                            
                            #(a)
                             for(;;){
                                //Do something
                             }
                             # equivalent
                             #(b)
                              while(true){
                                //Do something
                              }

                            
                          

Caution

  • Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below:
                            
                                for (int i=0; i<10; i++); //logical error
                                {
                                  System.out.println("i is " + i);
                                }
                                

                            
                          

Caution

  • while loop do not terminate with ;
  • In the case of the do loop, the following semicolon is needed to end the loop.
                            
                                int i=0; 
                                while (i < 10); //Logical Error
                                {
                                  System.out.println("i is " + i);
                                  i++;
                                }
                                
                                
                            
                          
                            
                               int i=0; 
                                do {
                                  System.out.println("i is " + i);
                                  i++;
                                } while (i<10); // This is correct
                                
                                
                            
                          

Which Loop to Use?

  • The three forms of loop statements, while, do-while, and for, are expressively equivalent;
  • You can write a loop in any of these three forms
  • 
                                    while(loop-condition){
                                        loop body
                                    }
    
                                    for(loop-condition){
                                        loop body
                                    }
                                    do{
                                        loop body
                                    }while(condition);
                                      

Recommendations

  • Use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known,as, for example, when you need to print a message 100 times
  • A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0
  • A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.
  • 
                                        while(loop-condition){
                                            loop body
                                        }
        
                                        for(loop-condition){
                                            loop body
                                        }
                                        do{
                                            loop body
                                        }while(condition);
                                          

Nested Loop

									public static void main(String[] args) {
                                        // Display the table heading
                                        System.out.println(" Multiplication Table");
                                    
                                        // Display the number title
                                        System.out.print("    ");
                                        for (int j = 1; j <= 9; j++)
                                          System.out.print("   " + j);
                                    
                                        System.out.println("\n-----------------------------------------");
                                    
                                        // Print table body
                                        for (int i = 1; i <= 9; i++) {
                                          System.out.print(i + " | ");
                                          for (int j = 1; j <= 9; j++) {
                                            // Display the product and align properly
                                            System.out.printf("%4d", i * j);
                                          }
                                          System.out.println();
                                        }
                                      }
									  
TestSum Example

                                            public static void main(String[] args) {
                                                // Initialize sum
                                                float sum = 0;
                                            
                                                // Add 0.01, 0.02, ..., 0.99, 1 to sum
                                                for (float i = 0.01f; i <= 1.0f; i = i + 0.01f)
                                                  sum += i;
                                            
                                                // Display result
                                                System.out.println("The sum is " + sum);
                                              }
                                              
                                             

Infinite Loop

  • In Java, an infinite loop occurs when the loop’s ending condition is not met.
  • An endless loop in Java is usually aprogramming error
  • it can sometimes be used intentionally, such as in a wait condition.
  • Github code samples Infinite Loop
  • 
                                             public static void main(String[] args) {
                                                     int count = 0;
                                                     while (count < 100) {
                                                         System.out.println("count:" + count);
                                                        count = count * 1;                // OOPS, does not change count
                                                     }
                                             }
                                         

Using break and continue

    break;

    continue;

    break and continue keywords

Break Keyword

    We can also use a labeled break statement to terminate a for, while or do-while loop.
  • Upon termination, the control flow is transferred to the statement immediately after the end of the outer loop:

					public static void main(String[] args) {
                        int i=0;
                        while(i<6){
                            if(i==3) break;
                            i++;
                        }
                        System.out.println("Loop stopped at " +i);
                      }
                    
					

Problem


                            // Stop the loop if i is 5;

                            for (int i = 0; i < 10; i++) {
                                if (i == 5) {
                                  ......
                              
                                }
                                System.out.println(i);
                              }
                        

Solution


                           
                            for (int i = 0; i < 10; i++) {
                                if (i == 5) {
                                  
                              break
                              ;
                                }
                                System.out.println(i);
                              }
                        

Continue Keyword

    The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

					public static void main(String[] args) {
                        int i=0;
                        while(i<5){
                            i++;
                            if(i==3) continue;
                            System.out.println("pass " +i);
                
                        }
                      }
                    
					

Problem


                            // In the loop, when the value is "4", jump directly to the next value.

                            for (int i = 0; i < 10; i++) {
                                if (i == 4) {
                                  
                                 .......
                                }
                                System.out.println(i);
                              }
                        

Solution


                           
                            for (int i = 0; i < 10; i++) {
                                if (i == 4) {
                                  
                              continue;
                                }
                                System.out.println(i);
                              }
                        

THE END

Questions/Suggestions

- HW 1
- Exam I
- Group
- Group Project Task