Chapter 4: Loops and Files

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 4: Loops and Files
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
Chapter 4: Loops and Files
Chapter 5 Loops.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Chapter The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Lecture 3 Looping and FIiling. 5-2 Topics – The Increment and Decrement Operators – The while Loop – Using the while Loop for Input Validation – The do.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Loops and Files Starting Out with Java From Control Structures.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING While Loop.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Topics Introduction to Repetition Structures
Loop Structures.
Lecture 4- Loops and Files
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5: Repetition Structures
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Topics Introduction to Repetition Structures
Lecture 4B More Repetition Richard Gesick
all loops initialization – set up the loop
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 4: Loops and Files
Chapter 4: Loops and Files by Tony Gaddis and Godfrey Muganda
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Outline Altering flow of control Boolean expressions
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
Chapter 6: Repetition Statements
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Ch.4 – 5 Topics The auto Increment and Decrement Operators
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Chapter 4: Loops and Files
Looping and Repetition
Presentation transcript:

Chapter 4: Loops and Files Monday October 9th

The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number + 1; number = number – 1; Using the ++ or –– unary operators, this task can be completed quickly. number++; or ++number; number--; or --number;

IncrementDecrement.java int number = 4; // number starts out with 4 System.out.println("number is " + number); System.out.println("I will increment number."); number++; System.out.println("Now, number is " + number); System.out.println("I will decrement number."); number--; 5 4

Differences Between Prefix and Postfix When an increment or decrement are the only operations in a statement, there is no difference between prefix and postfix notation. When used in an expression: prefix notation indicates that the variable will be incremented or decremented before the rest of the equation. postfix notation indicates that the variable will be incremented or decremented after the rest of the equation.

Example: Prefix.java int number = 4; // number starts out with 4 System.out.println("number is " + number); System.out.println("I will increment number."); ++number; System.out.println("Now, number is " + number); System.out.println("I will decrement number."); --number; 5 4

The while Loop Java provides three different looping structures. The while loop has the form: while(condition){ statements; } While the condition is true, the statements will execute repeatedly. The while loop is a pretest loop, which means that it will test the value of the condition prior to executing the loop.

The while Loop Care must be taken to set the condition to false somewhere in the loop so the loop will end. Loops that do not end are called infinite loops. A while loop executes 0 or more times since if the condition is false, the loop will not execute.

Example: WhileLoop.java int number = 1; while (number <= 5) { System.out.println("Hello"); number++; } System.out.println("That's all!"); number Output 1 2 3 4 5 6 Hello

Infinite Loops In order for a while loop to end, the condition must become false. int x = 20; while(x > 0){ System.out.println(“x is greater than 0”); } The variable x never gets decremented so it will always be greater than 0.

Infinite Loops In order for a while loop to end, the condition must become false. { int x = 20; while(x > 0){ System.out.println(“x is greater than 0”); x--; } The variable x never gets decremented so it will always be greater than 0. Adding the x-- above fixes the problem.

The while Loop for Input Validation Input validation is the process of ensuring that user input is valid.

Example: Input Validation number = Integer.parseInt(JOptionPane.showInputDialog( “Enter a number in the " + "range of 1 through 100:” ) ) while (number < 1 || number > 100) { System.out.println("That number is invalid."); "range of 1 through 100:” ) ); }

The do-while Loop The do-while loop is a post-test loop, which means it will execute the loop prior to testing the condition. The do-while loop, more commonly called a do loop, takes the form: do{ statements }while(condition);

Example: TestAverage1.java int score1, score2, score3; // Three test scores double average; // Average test score char repeat; // To hold 'y' or 'n‘ String input; // To hold input System.out.println("This program calculates the " + "average of three test scores.");

Example: TestAverage1.java do { score1 = Integer.parseInt( JOptionPane.showInputDialog ( "Enter score #1: “)); score2 = Integer.parseInt( JOptionPane.showInputDialog ( "Enter score #2: “)); score3 = Integer.parseInt( JOptionPane.showInputDialog ( "Enter score #3: “));

Example: TestAverage1.java average = (score1 + score2 + score3) / 3.0; JOptionPane.showMessageDialog(null, "The average is " + average); "Would you like” + “ to average another set of test scores?"); input = JOptionPane.showInputDialog(( "Enter Y for yes or N for no: "); repeat = input.charAt(0); // Get the first char. } while (repeat == 'Y' || repeat == 'y');

The for Loop The for loop is a specialized form of the while loop, meaning it is a pre-test loop. The for loop allows the programmer to initialize a control variable, test a condition, and modify the control variable all in one line of code. The for loop takes the form: for(initialization; test; update) { loop statements; }

Example: Squares.java int number; // Loop control variable System.out.println("Number Number Squared"); System.out.println("-----------------------"); for (number = 1; number <= 10; number++) { System.out.println(number + "\t\t" + number * number); }

The Sections of The for Loop The initialization section of the for loop allows the loop to initialize its own control variable. The test section of the for statement acts in the same manner as the condition section of a while loop. The update section of the for loop is the last thing to execute at the end of each loop.

Example: UserSquares.java int number; // Loop control variable int maxValue; // Maximum value to display System.out.println("I will display a table of " + "numbers and their squares."); maxValue = Integer.parseInt( JOptionPane.showInputDialog ( "How high should I go? ")); // Display the table. System.out.println("Number Number Squared"); System.out.println("-----------------------"); for (number = 1; number <= maxValue; number++) { System.out.println(number + "\t\t" + number * number); }

The for Loop Initialization The initialization section of a for loop is optional; however, it is usually provided. Typically, for loops initialize a counting variable that will be tested by the test section of the loop and updated by the update section. The initialization section can initialize multiple variables. Variables declared in this section have scope only for the for loop.

The Update Expression The update expression is usually used to increment or decrement the counting variable(s) declared in the initialization section of the for loop. The update section of the loop executes last in the loop. The update section may update multiple variables. Each variable updated is executed as if it were on a line by itself.

Modifying The Control Variable It is bad programming style to update the control variable of a for loop within the body of the loop. The update section should be used to update the control variable. Updating the control variable in the for loop body leads to hard to maintain code and difficult debugging.

Multiple Initializations and Updates The for loop may initialize and update multiple variables. for(int i = 5, int j = 0; i < 10 || j < 20; i++, j+=2){ loop statements; } Note that the only parts of a for loop that are mandatory are the semicolons. for(;;){ }//infinite loop. If left out, the test section defaults to true.

Running Totals Loops allow the program to keep running totals while evaluating data. Imagine needing to keep a running total of user input.

Example: TotalSales.java int days; // The number of days double sales; // A day's sales figure double totalSales; // Accumulator String input; // To hold the user's input // Create a DecimalFormat object to format output. DecimalFormat dollar = new DecimalFormat("#,##0.00"); // Get the number of days. input = JOptionPane.showInputDialog("For how many days " + "do you have sales figures?"); days = Integer.parseInt(input);

Example: TotalSales.java for (int count = 1; count <= days; count++) { input = JOptionPane.showInputDialog("Enter the ” +“sales for day " + count + ": "); sales = Double.parseDouble(input); totalSales += sales; // Add sales to totalSales. } JOptionPane.showMessageDialog(null, "The total sales are $" + dollar.format(totalSales));

Sentinel Values Sometimes (usually) the end point of input data is not known. A sentinel value can be used to notify the program to stop acquiring input. If it is a user input, the user could be prompted to input data that is not normally in the input data range (i.e. –1 where normal input would be positive.)

Example: SoccerPoints.java int points; // Game points int totalPoints = 0; // Accumulator initialized to 0 // Display general instructions. System.out.println("Enter the number of points your team"); System.out.println( "has earned for each game this season."); System.out.println("Enter -1 when finished."); System.out.println(); // Get the first number of points. points = Integer.parseInt( JOptionPane.showInputDialog( "Enter game points or -1 to end: "));

SoccerPoints.java // Accumulate the points until -1 is entered. while (points != -1) { totalPoints += points; points = Integer.parseInt( JOptionPane.showInputDialog( "Enter game points or -1 to end: ")); } // Display the total number of points. System.out.println("The total points are " + totalPoints);

Nested Loops Like if statements, loops can be nested. If a loop is nested, the inner loop will execute all of its iterations for each time the outer loop executes once. for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) loop statements; The loop statements in this example will execute 100 times.

Example: Clock.java // Create a DecimalFormat object to format output. DecimalFormat fmt = new DecimalFormat("00"); // Simulate the clock. for (int hours = 1; hours <= 12; hours++) { for (int minutes = 0; minutes <= 59; minutes++) for (int seconds = 0; seconds <= 59; seconds++) System.out.print(fmt.format(hours) + ":"); System.out.print(fmt.format(minutes) + ":"); System.out.println(fmt.format(seconds)); }

The break And continue Statements The break statement can be used to abnormally terminate a loop. The use of the break statement in loops bypasses the normal mechanisms and makes the code hard to read and maintain. It is considered bad form to use the break statement in this manner.

The continue Statement The continue statement will cause the currently executing iteration of a loop to terminate and the next iteration will begin. The continue statement will cause the evaluation of the condition in while and for loops. Like the break statement, the continue statement should be avoided because it makes the code hard to read and debug.

Deciding Which Loops to Use The while loop: Performs the test before entering the loop Use it where you do not want the statements to execute if the condition is false in the beginning. The do-while loop: Performs the test after entering the loop Use it where you want the statements to execute at least one time. The for loop: Use it where there is some type of counting variable that can be evaluated.