1 / 24

Java Programming

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.

isanne
Download Presentation

Java Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Programming Loops Chapter 6

  2. 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?

  3. 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; • } • } • }

  4. 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

  5. Loop Structure

  6. 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

  7. 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

  8. 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

  9. 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

  10. Incrementing Shortcut • Note often used style of incrementing counter = counter + 1; counter++; Same result

  11. 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

  12. Shortcut Arithmetic Operators

  13. 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

  14. 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); • } • }

  15. 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

  16. The for Loop for (initial-action; loop-continuation-condition; action-after-each-iteration) { Statement(s); }

  17. 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!"); • } • } • }

  18. 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

  19. 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++; • } • } • }

  20. 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

  21. 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

  22. 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"); • } • } • }

  23. 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.

  24. 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); • } • }

More Related