240 likes | 407 Views
Java Programming. Loops Chapter 6. Motivations. Suppose that you need to print the string "Hello World!" a hundred times. It would be tedious to have to write the following statement a hundred times: System.out.println ("Hello World!"); So, how do you solve this problem?. Loops.
E N D
Java Programming Loops Chapter 6
Motivations Suppose that you need to print the string "Hello World!" a hundred times. It would be tedious to have to write the following statement a hundred times: System.out.println("Hello World!"); So, how do you solve this problem?
Loops • Loop • Structure that allows repeated execution of a block of statements • class Loop { • public static void main(String[ ] args) { • int count = 0; • while (count < 100) { • System.out.println("Hello World!"); • count = count + 1; • } • } • }
Loops • Java has three types of loop statements: the while, the do-while, and the for statements: • while • Loop-controlling Boolean expression is the first statement • do...while • Loop-controlling Boolean expression is the last statement • for • A concise format in which to execute loops • The code that is repeated in a loop is called the body of the loop • Each repetition of the loop body is called an iteration of the loop
The while Loop • while loop • Executes body of statements continually • As long as Boolean expression that controls entry into loop continues to be true • Consists of keyword while • Followed by Boolean expression within parentheses • Followed by body of loop; can be single statement or block of statements surrounded by curly braces
Trace while Loop Initialize count int count = 0; while (count < 2) { System.out.println("Hello World!"); count = count + 1; } (count < 2) is true (count < 2) is false Print Hello World Increase count by 1 Exit the loop count = 0 count = 1 count = 2
The while Loop • Counting loops • Loop must run specific number of times • Variable incremented/decremented required number of times • Sentinel controlled loops • Task must be repeated until a certain condition is true • That condition is the sentinel
The while Loop • Infinite loop • Loop that never ends • Can result from mistake in while loop • Suspect infinite loop • Same output displayed repeatedly • Screen remains idle for extended period of time • Exit from infinite loop • Press and hold Ctrl • Press C or Break
Incrementing Shortcut • Note often used style of incrementing counter = counter + 1; counter++; Same result
Shortcut Arithmetic Operators • Java provides shortcuts for incrementing and accumulating: += add and assign (also use ++) -= subtract and assign (also use -- ) *= multiply and assign /= divide and assign %= remainder and assign
The do...whileLoop • do...whileloop • Posttest loop • Checks value of loop control variable • At bottom of loop • After one repetition has occurred • Performs task at least one time • Use curly brackets to block statement • Even with single statement
The do...whileLoop • Boolean condition is at the end of the loop • Use a semicolon after the condition statement • class Loop { • public static void main(String[ ] args) { • int count = 0; • do { • System.out.println("Hello World!"); • count = count + 1; • } while (count < 100); • } • }
The for Loop • for Loop • Used when definite number of loop iterations is required • One convenient statement • Assign starting value for loop control variable • Test condition that controls loop entry • Alter loop control variable
The for Loop for (initial-action; loop-continuation-condition; action-after-each-iteration) { Statement(s); }
The forLoop • Three parts within the for statement • Initial value (i = 0) • Condition ( i < 100) • Update ( i = i + 1) • class Loop { • public static void main(String[ ] args) { • int i; • for (i = 0; i < 100; i++) { • System.out.println("Hello World!"); • } • } • }
Nested Loops • Inner and outer loops • Inner loop must be entirely contained in outer loop • Loops can never overlap • Consider code to generate a two dimensional pattern of asterisks • Nested loop solution • Inner loop displays each star in a row • Outer loop drives the creation of the rows
import java.util.Scanner; • class Square { • public static void main(String[ ] args) { • int rowCount = 1; • System.out.print("What is the length of the square? "); • Scanner input = new Scanner(System.in); • int sideLength = input.nextInt( ); • while (rowCount <= sideLength) { • int starCount = 1; • while (starCount<= sideLength) { • System.out.print("* "); • starCount ++; • } • System.out.println( ); • rowCount++; • } • } • }
Be Careful • Don’t insert a semicolon at the end of a while or for clause (except for the do…while) • Don’t forget to block multiple statements that should execute in a loop • Don’t make the mistake of checking for invalid data using a decision instead of a loop • Use integer counters to avoid floating point errors • Don’t repeat steps within a loop that could just as well be placed outside the loop
Guess the number • Let’s update our Guess the number game • If guessed correctly, you win • Otherwise print that the guess is too high or too low and to guess again • Continue till guessed correctly
import java.util.Scanner; • class GuessingGame { • public static void main(String[ ] args) { • int guess = 0; • System.out.print("Enter an integer from 1 to 100: "); • Scanner input = new Scanner(System.in); • int number = (int)(Math.random() * 100)+1; • while (guess != number) { • // Prompt the user to guess the number • System.out.print("\nEnter your guess: "); • guess = input.nextInt( ); • if (guess == number) • System.out.println("Yes, the number is " + number); • else if (guess > number) • System.out.println("Your guess is too high"); • else • System.out.println("Your guess is too low"); • } • } • }
Finding the Greatest Common Divisor • Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. • Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? • Let the two input integers be n1 and n2. • You know number 1 is a common divisor, but it may not be the greatest commons divisor. • Check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2.
import java.util.Scanner; • public class GreatestCommonDivisor { • public static void main(String[ ] args) { • Scanner input = new Scanner(System.in); • System.out.print("Enter first integer: "); • int n1 = input.nextInt( ); • System.out.print("Enter second integer: "); • int n2 = input.nextInt( ); • int gcd = 1; • int k = 2; • while (k <= n1 || k <= n2) { • if (n1 % k == 0 && n2 % k == 0) • gcd = k; • k++; • } • System.out.println("The greatest common divisor for " + n1 + • " and " + n2 + " is " + gcd); • } • }