Thursday, 26 April 2018

Core Java: Loop Statemets

there are a few types of loops: for, while-do, and do-while.
 
Syntax
Example
Flowchart
// for-loop
for (initialization; test; post-processing) {
   body;
}

// Sum from 1 to 1000
int sum = 0;
for (int number = 1; number <= 1000; ++number) {
   sum += number;
}

// while-do loop
while ( test ) {
   body;
}

int sum = 0, number = 1;
while (number <= 1000) {
   sum += number;
   ++number;
}

// do-while loop
do {
   body;
}
while ( test ) ;
int sum = 0, number = 1;
do {
   sum += number;
   ++number;
} while (number <= 1000);

The difference between while-do and do-while lies in the order of the body and condition. In while-do, the condition is tested first. The body will be executed if the condition is true and the process repeats. In do-while, the body is executed and then the condition is tested. Take note that the body of do-while will be executed at least once vs. possibly zero for while-do. Similarly, the for-loop's body could possibly not executed.
Example: Suppose that your program prompts user for a number between 1 to 10, and checks for valid input. A do-while loop with a boolean flag could be more appropriate as it prompts for input at least once, and repeat again and again if the input is invalid.



// Input with validity check
boolean valid = false;
int number;
do {
  // prompt user to enter an int between 1 and 10
  ......
  // if the number entered is valid, set done to exit the loop
  if (number >=1 && number <= 10) {
     valid = true;
  }
} while (!valid);   // Need a semi-colon to terminate do-while
Example: Below is an example of using while-do with a boolean flag. The boolean flag is initialized to false to ensure that the loop is entered.
// Game loop
boolean gameOver = false;
while (!gameOver) {
   // play the game
   ......
   // Update the game state
   // Set gameOver to true if appropriate to exit the game loop
   ......
}

Empty for-loop
for ( ; ; ) { body } is known as an empty for-loop, with empty statement for initialization, test and post-processing. The body of the empty for-loop will execute continuously (infinite loop). You need to use a break statement to break out the loop.

for-loop with Comma Separator
You could place more than one statement in the initialization and post-processing, separated with commas (instead of the usual semi-colon). For example,
for (int row = 0, col = 0; row < SIZE; ++row, ++col) {
   // Process diagonal elements
   ......
}

 Nested Loops
 
Try out the following program, which prints a 8-by-8 checker box pattern using nested loops, as follows:
 
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
 * Print a square pattern
 */
public class PrintSquarePattern {    // Save as "PrintSaurePattern.java"
   public static void main(String[] args) {
      int size = 8;
      for (int row = 1; row <= size; ++row) {     // Outer loop to print all the rows
         for (int col = 1; col <= size; ++col) {  // Inner loop to print all the columns of each row
            System.out.print("# ");
         }
         System.out.println();   // A row ended, bring the cursor to the next line
      }
   }
}
 
 
This program contains two nested for-loops. The inner loop is used to print a row of eight "# ", which is followed by printing a newline. The outer loop repeats the inner loop to print all the rows.
Suppose that you want to print this pattern instead (in program called PrintCheckerPattern):
 
# # # # # # # #
 # # # # # # # #
# # # # # # # #
 # # # # # # # #
# # # # # # # #
 # # # # # # # #
# # # # # # # #
 # # # # # # # #
 
You need to print an additional space for even-number rows. You could do so by adding the following statement before Line 8.
 
if ((row % 2) == 0) {   // print a leading space for even-numbered rows
   System.out.print(" ");
}
 
TRY:
 
Print these patterns using nested loop (in a program called PrintPattern1x). Use a variable called size for the size of the pattern and try out various sizes. You should use as few print() or println() statements as possible. 
 
 
 # * # * # * # *    # # # # # # # #    # # # # # # # #    1                                1
# * # * # * # *     # # # # # # #        # # # # # # #    2 1                            1 2
 # * # * # * # *    # # # # # #            # # # # # #    3 2 1                        1 2 3
# * # * # * # *     # # # # #                # # # # #    4 3 2 1                    1 2 3 4
 # * # * # * # *    # # # #                    # # # #    5 4 3 2 1                1 2 3 4 5
# * # * # * # *     # # #                        # # #    6 5 4 3 2 1            1 2 3 4 5 6
 # * # * # * # *    # #                            # #    7 6 5 4 3 2 1        1 2 3 4 5 6 7
# * # * # * # *     #                                #    8 7 6 5 4 3 2 1    1 2 3 4 5 6 7 8
     (a)                  (b)                (c)                (d)                (e)
 
Hints:

The equations for major and opposite diagonals are row = col and row + col = size + 1. Decide on what to print above and below the diagonal. 
 
Print the timetable of 1 to 9, as follows, using nested loop. (Hints: you need to use an if-else statement to check whether the product is single-digit or double-digit, and print an additional space if needed.) 
 
 1  2  3  4  5  6  7  8  9
 2  4  6  8 10 12 14 16 18
 ...... 
 
 
Print these patterns using nested loop. 
 
 
 
# # # # # # #      # # # # # # #      # # # # # # #      # # # # # # #      # # # # # # #
#           #        #                          #          #       #        # #       # #
#           #          #                      #              #   #          #   #   #   #
#           #            #                  #                  #            #     #     #
#           #              #              #                  #   #          #   #   #   #
#           #                #          #                  #       #        # #       # #
# # # # # # #      # # # # # # #      # # # # # # #      # # # # # # #      # # # # # # #
     (a)                 (b)               (c)                (d)                (e)

Some Issues in Flow Control
 
Dangling Else: The "dangling else" problem can be illustrated as follows:
if (i == 0)
   if (j == 0)
      System.out.println("i and j are zero");
else System.out.println("i is not zero");   // intend for the outer-if
 
The else clause in the above codes is syntactically applicable to both the outer-if and the inner-if. Java compiler always associate the else clause with the innermost if (i.e., the nearest if). Dangling else can be resolved by applying explicit parentheses. The above codes are logically incorrect and require explicit parentheses as shown below.
 
if ( i == 0) {
   if (j == 0) System.out.println("i and j are zero");
} else {
   System.out.println("i is not zero");   // non-ambiguous for outer-if
}
 
Endless loop: The following constructs:
 
while (true) { ...... }
is commonly used. It seems to be an endless loop (or infinite loop), but it is usually terminated via a break or return statement inside the loop body. This kind of code is hard to read - avoid if possible by re-writing the condition.

No comments:

Post a Comment

Please write your view and suggestion....