Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #6 Loops
What is Loop? A loop can be used to tell a program to execute statements repeatedly. Java provides a powerful construct called a loop that controls how many times an operation or a sequence of operations is to be performed in succession. Java provides three types of loop statements: while loops, do-while loops, and for loops. The while Loop A while loop executes statements repeatedly while the condition is true. The syntax for the while loop is: while (loop-continuation-condition) { // Loop body Statement(s); And the flowchart for while loop is: Here is an example that uses while loop to print a statement one hundred times to the console. int count = 0; while (count < 100) { // <-- the condition System.out.println("Welcome to Java!"); //loop body count++; 2
Note that The loop-continuation-condition must always appear inside the parentheses. The braces enclosing the loop body can be omitted only if the loop body contains one statement. Ex: Consider the following algorithm to generate a sequence of numbers. 1. Start with an integer n. 2. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. 3. Repeat this process with the new value of n, terminating when n = 1. Write a program to reads a positive integer n and generates a sequence of numbers until 1. int n = input.nextint(); while (n > 1) { System.out.print(n + " "); if (n % 2 == 0) n /= 2; else n = n * 3 + 1; System.out.println(n); Ex: Write a program that reads a line of text and uses indexof method to determine the number of a specific letter in the text. Uppercase and lowercase letters should be counted together. System.out.println("Enter the text: "); String text = input.nextline().tolowercase(); System.out.print("Enter the letter: "); char letter = input.next().charat(0); int counter = 0; int lastindexfound = text.indexof(letter); while (lastindexfound!= -1) { counter++; lastindexfound = text.indexof(letter, lastindexfound + 1); System.out.println(counter + " Times."); 3
break Statement You can use break in a loop to immediately terminate the loop. Ex: Write a program that asks the user to type a positive integer. When the user types a negative value the program writes 'ERROR' and asks for another value. When the user types 0 that means that the last value has been typed and the program must write the average of the positive integers. If the number of typed values is zero the program writes 'NO AVERAGE'. int n, sum = 0, count = 0; while (true) { System.out.print("Enter a positive number: "); n = input.nextint(); if (n == 0) { break; else if (n < 0) { System.out.println("Error! try again"); else { sum += n; count++; if (count > 0) System.out.println("Average is: " + (sum * 1.0 / count)); else System.out.println("No Average"); The do-while Loop A do-while loop is the same as a while loop except that it executes the loop body first and then checks the loop continuation condition. The do-while loop is a variation of the while loop. Its syntax is: do { // Loop body; Statement(s); while (loop-continuation-condition); 4
Note the semicolon after the condition. And the flowchart for do-while loop is: Ex: Re-write the previous example using do-while loop. int n, sum = 0, count = 0; do { System.out.print("Enter a positive number: "); n = input.nextint(); if (n < 0) { System.out.println("Error! try again"); else if (n > 0) { sum += n; count++; while (n!= 0); if (count > 0) System.out.println("Average is: " + (sum * 1.0 / count)); else System.out.println("No Average"); Note that we didn t need to use break statement. 5
The for Loop The syntax of a for loop is: for (initial-action; loop-continuation-condition; action-aftereach-iteration) { // Loop body Statement(s); And the flowchart of for loop is: Ex: Write a program that counts how many uppercase letters exist in a given string. String line = input.nextline(); int counter = 0; for (int i = 0; i < line.length(); i++) { if (Character.isUpperCase(line.charAt(i))) counter++; System.out.println(counter); 6
continue Statement You can use continue in a loop to terminate the current iteration of a loop. Ex: Write a program that prints all numbers between 0 and 100, except that which divide by 7. for (int i = 0; i <= 100; i++) { if (i % 7 == 0) continue; System.out.println(i); Note: In IntelliJ IDEA you can use the template to write for loop quickly. Type fori then press TAB. Lab Work Ex1: Write a program that prompts the user to enter an integer and displays a rectangle as follows: System.out.println("Enter a number: "); int num = input.nextint(); for (int i = 1; i <= num; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); System.out.println(); 7
Ex2: Write a program that asks the user to type 10 integers and prints the smallest value. int n = input.nextint(); int min = n; for (int i = 0; i < 9; i++) { n = input.nextint(); if (n < min) min = n; System.out.println("The smallest number is: " + min); Ex3: Write a program to read a file contains unknown number of lines, each line contains exactly two integers A and B separated by a space. For each line, print the sum of both numbers, in the following format: Line #N: S Where N is the line number, and S is the sum of two numbers in that line. Here is a sample input: And here is a sample output: Line #1: 9 Line #2: 54 Line #3: 158 Line #4: 92 Hint: input.hasnext() method returns true if this scanner has another token in its input. 8
Scanner input = new Scanner(new File("input.txt")); int a, b, line = 1; while (input.hasnext()) { a = input.nextint(); b = input.nextint(); System.out.println("Line #" + line + ": " + (a + b)); line++; Homework 1. Write a program that prompts the user to enter a string and displays the characters at odd positions. Sample Input Hello World! Welcome to Java Sample Output HloWrd Wloet aa 2. The following loop uses while syntax. Convert it to use for syntax. int x; Scanner sc = new Scanner(System.in); x = sc.nextint(); while (x!= 10) { System.out.println(x + "\t"); x = sc.nextint(); 3. What is the output of the following code for (int x = 1; x <= 5; x++) { for (int y = 1; y <= x; y++) System.out.print(x + "\t"); 4. Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is 5 and the occurrence count for 5 is 4. Good Luck 9