chapter 5 loops

Download Chapter 5 Loops

Post on 05-Jan-2016

23 views

Category:

Documents

0 download

Embed Size (px)

DESCRIPTION

Chapter 5 Loops. Section 1 - While Loops Section 2 - For Loops Section 3 - printf Statements Section 4 - Loop Errors Section 5 - Nested Control Statements & Loop Errors Section 6 - Input & Output GUI Dialog Boxes. Go. Go. Go. Go. Go. Go. Chapter 5 Section 1 While Loops. - PowerPoint PPT Presentation

TRANSCRIPT

  • Chapter 5LoopsSection 1 - While LoopsSection 2 - For LoopsSection 3 - printf StatementsSection 4 - Loop ErrorsSection 5 - Nested Control Statements & Loop ErrorsSection 6 - Input & Output GUI Dialog BoxesGoGoGoGoGoGo

    Fundamentals of Java

  • Chapter 5 Section 1While Loops

    Fundamentals of Java

  • *5.1 What are Control Statements?We call .

    if statementsif-else statementswhile loopsand for loops

    control statements

    because they control the order of execution in a Java program.

  • *5.1 Definition of a While LoopIn Java you can execute a segment of code over and over again while a boolean condition evaluates to true. When the boolean condition becomes false, the while loop will stop. There should be some code in the loop to make it stop, otherwise you will have an infinite loop (never-ending loop).

    A while loop looks like this:

    while (some boolean condition is true) {}

    No code is executed if the boolean condition is initially false. The loop is skipped!

  • *5.1 A Count Up while Loop ExampleA count-up while loop can be written to sum the integers from 1 to 3:

    int sum = 0;int cntr = 1; while (cntr

  • *5.1 Tracing a Count Up while LoopIt is important to be able to trace the order of execution of a while loop to be able to fully understand how it works:

    int sum = 0;int cntr = 1; 1while (cntr

  • *5.1 Skeleton of a Count Up while LoopIf you initially think about the problem of summing the numbers from 1 to 100, you should conclude that a loop is needed that will run 100 times. So the place to start is just to think about the basic parts of the loop that you need. Dont worry about the mathematics or the work to be done inside the loop. Pull the necessary components together that will give you a loop that will run 100 times. Here is where you should start:

    int cntr = 1; while (cntr

  • *5.1 General Form of a while loopThe while loop executes statements inside its body repeatedly for as long as its condition remains true.Every time the statements inside a while loop run, we say one iteration, one pass, or one repetition has occurred.

    while (condition) { // saves lines by putting { on same line of conditionstatement;statement;} No semicolon goes here!

    while (condition) No semicolon goes here!{// adds readability by putting curly brace { on separate linestatement;statement;}

    No curly braces required for just one line of code in the loop.

  • *5.1 Count-Controlled while LoopsThe variable cntr is the counter variable or loop control variable (lcv) and is declared and initialized before the while loop.This while loop repeats 100 times, because when the loop is encountered the value of cntr is 1 and it is incremented by 1 every time the body of the loop runs. The loop will run the final time when cntr is 100 and then when it becomes 101 inside the loop, then the loop condition evaluates to false and the body of the loop wont execute anymore.Consider the following code that sums the integers from 1 to 100:

    int sum = 0;int cntr = 1;while(cntr

  • *5.1 Count Down while LoopsCountdown Loop code:int sum = 0;int cntr = 100;while(cntr >= 1){sum += cntr;cntr--;}Note the code in the loop is exactly the same. Only the loop header and the initiaization value of the lcv have been changed. Compare the two codes to see the differences.The following code uses a variation of the previous code to sum the integers from 100 down to 1. We call this a count down loop:Original code:int sum = 0;int cntr = 1;while(cntr
  • *5.1 Varying while Loops ConditionsWhat if the boolean expression of the original code was changed from:cntr
  • *5.1 A Count-Down While Loop ExampleYou can make a loop control variable decrease in value as well as increase. It can decrease by 1 or by any other value you indicate. Here number is the loop control variable.

    int number = 25;while (number >= 10){System.out.print("The square root of " + number); System.out.println( is " + Math.sqrt(number));number -= 5;}Output in console window:The square root of 25 is 5.0The square root of 20 is 4.47213595499958The square root of 15 is 3.872983346207417The square root of 10 is 3.1622776601683795

  • *5.1 A Count-Down While Loop ExampleWhat if the boolean expression was changed from:number >= 10 to number > 10

    int number = 25;while (number > 10){System.out.print("The square root of " + number); System.out.println( is " + Math.sqrt(number));number -= 5;}The loop runs one less times and the Output is:The square root of 25 is 5.0The square root of 20 is 4.47213595499958The square root of 15 is 3.872983346207417

    Fundamentals of Java

  • *5.1 Calculating a Factorial ExampleSystem.out.print("Enter a number greater than zero: ");int number = reader.nextInt();

    int product = 1;int cntr = 1;

    while (cntr

  • *5.1 Task-Controlled While LoopsA loop can execute until some task is accomplished. This code seeks to find the value of number once sum is greater than 1,000,000.

    int sum = 0;int number = 0;while ( sum

  • *5.1 Interesting While Loop ExampleCode Example: Generate a random integer between -5 and 5 inclusive and store it in x. If x is positive find the square root of all values between 1 and x and print them out, otherwise do nothing.

    int x = (int) (Math.random() * 11 ) - 5;while (x > 0) {double root = Math.sqrt(x);System.out.println(The square root of x is + root);x--;}

    Notice that if the value stored in x is between -5 and 0 inclusive, the loop will NOT run at all.Also notice that when x is positive, the loop will run and then x will be decremented by 1 and eventually x will become 0 and when it does then 0 > 0 evaluates to false and the loop stops.

    Fundamentals of Java

  • *5.1 User-Controlled While Loop ExampleThe following code sums all the integers between two integers (inclusive) entered from the keyboard:

    Scanner reader = new Scanner (System.in);System.out.print(Enter a starting value: );int startingValue = reader.nextInt();System.out.print(Enter an ending value greater than starting value: );int endingValue = reader.nextInt();int sum = 0;int cntr = startingValue;while (cntr

  • *5.1 Order & Structure of a While LoopInitialize the loop control variable and other variables.Test the condition to try to enter the while loop.If successful entry, execute the body of the loop and then perform calculations and change the lcv and other variables.When the condition becomes false, the loop stops without executing the body.initialize loop control variable // initializewhile (condition) // test the condition{// execute the body of loopperform calculations and change variables involved in the condition}

  • *5.1 Using a while (true) loop with Break Since true is a valid boolean value, a while(true) loop can be used.A while (true) loop continues to run until some condition makes it stop. This can be done by embedding a break statement inside an if statement inside the loop, so that when the if condition becomes true, the break statement will be executed and the loop will immediately stop.while (true) { System.out.print(Enter a number or -1 to quit: ); int x = reader.nextInt(); if (x == -1) break;. // lines of code that use x if it is not -1} -1 is called the sentinel because it makes the loop stop

  • 5.1 A while (true) loop Example Here is a while-true loop example that

    while(true){System.out.print("Enter the person's age or -1 to quit: ");age = reader.nextInt();

    if (age == -1)break;

    reader.nextLine(); // consume the new line character

    System.out.print("Enter the person's name: ");name = reader.nextLine();

    if(age < 0 || age > 120)System.out.println("There is NO WAY you are alive " + name);else{System.out.println("The name of the person is: " + name);System.out.println("The age of the person is: " + age);}} // end of while(true) loop*

    Fundamentals of Java

  • *5.1 Flow Chart for The while StatementNotice the return arrow after the last statement in the loop. It makes contact above the condition diamond.All the statements inside the loop go here.

  • Chapter 5 Section 2For Loops

    Fundamentals of Java

  • *5.2 Definition of a For LoopIn Java you can execute a segment of code over and over again using a for loop. The key difference between a for and a while loop is you can place the declaration and initialization of the lcv (loop control variable), the test condition, and the lcv update statement all in the for loop header.

    A for loop looks like this:

    for (declare & initialize lcv; test condition; update lcv) {}

    Here no code is executed if the test condition is initially false.Note the curly braces { } that encompass all of the statements inside the for loop body.

    Fundamentals of Java

  • *5.2 A Simple for Loop Exampleint sum = 0;for (int cntr = 1; cntr
  • *5.2 The for Loop Order of ExecutionIt is important to be able to trace the order of execution of a for loop. This will help you fully understand what is going on.The order of execution is indicated with the blue numbers.int sum = 0;

    for (int cntr = 1; cntr

  • *5.2 A Second While & For Loop ComparisonCompare the parts of the for loop and while loop versions of the code that sums all of the integers from 1 to 100:int sum = 0;for (int cntr = 1; cntr
  • *5.1 Skeleton of a Count Up for LoopIf you initially think about the problem of summing the numbers from 1 to 100, you should conclude that a loop is needed that will run 100 times. So the place t

Recommended

View more >