Full file at

Size: px
Start display at page:

Download "Full file at"

Transcription

1 Chapter 3 Flow of Control Key Terms parentheses, p. 95 if-else, p. 95 if-else with multiple statements, p. 96 compound statements, p. 96 indenting, p. 98 multiway if-else, p. 98 switch statement, p. 101 controlling expression, p. 102 case labels, p. 102 break, p. 102 default, p. 102 conditional operator, p. 106 Boolean expression, p. 107 lexicographical ordering, p. 110 compareto, p. 110 comparetoignorecase, p. 111 && means and, p. 113 means or, p. 113 truth tables, p. 115 Boolean variables in assignments, p. 116 short-circuit evaluation, p. 118 lazy evaluation, p. 118 complete evaluation, p. 118 precedence rules, p. 119 associativity rules, p. 119 higher precedence, p. 119 binding, p. 122 side effects, p. 123 while and do-while compared, p. 126 executing the body zero times, p. 128 algorithm, p. 128 pseudocode, p. 128 sentinel values, p. 131 for statement, p. 132 empty statement, p. 137 infinite loop, p. 138 nested loop, p. 139 break statement, p. 142 continue statement, p. 142 label, p. 142

2 off-by-one error, p. 144 incremental development, p. 150 cod review, p. 150 pair programming, p. 150 assertion, p. 151 assert, p. 151 assertion check, p. 152 Brief Outline 3.1 Branching Mechanism If-else statements Omitting the else Compound Statements Nested Statements Multiway if-else Statement The switch Statement The Conditional Operator 3.2 Boolean Expressions Simple Boolean Expressions Lexicographic and Alphabetic Order Building Boolean Expressions Evaluating Boolean Expressions Short-Circuit and Complete Evaluation Precedence and Associativity Rules 3.3 Loops While statement and do-while statement Algorithms and Pseudocode The for Statement The Comma in for Statements Nested Loops The break and continue Statements The exit Statement 3.4 Debugging Loop Bugs Tracing Variables General Debugging Techniques Preventive Coding Assertion Checks Teaching Suggestions This chapter discusses flow of control using both selection and iteration. The if-statement and loops are introduced both in this chapter. With both topics in one chapter, it is conceivable that this chapter will take longer for students to work through than many of the others in the text.

3 Branching, or selection, is introduced using the if-statement, the if-else statement, and the switch statement. Multiple paths and therefore, nested if-else statements are introduced. As the last form of selection available, the conditional operator is introduced at the end of the chapter. The coverage of the conditional operator is optional and can be omitted. The section on Boolean expressions follows the introduction of selection. However, some instructors might choose to put the second section before the first so that more complicated conditions on if-statements can be introduced right away. The third section on looping introduces all three looping constructs available inside Java. Loops can pose many challenges for students as illustrated by the Pitfall sections in the chapter. Having all of these tools available to them, students can write some fairly complex programs at the end of this chapter. However, what usually begins to happen is that students will write code that has errors. Finding these errors can be tedious and time-consuming. The last section on tracing loops, common loop bugs, and debugging is included as a way to help students begin to understand how to track down their errors in code. An option that would be useful to them if it is available would be to introduce and discuss the use of your computing environment s debugger at this time. Key Points If-else statement & Multiway if-else Statement. There are many ways to give the program a sense of choice or branching. First, we can use an if-statement by itself without an else. This allows us the option to do something or skip over it. We can also use an if-else statement, which allows us to take one path or another. Lastly, we can use combinations of these to have more than two choices for execution. As the number of paths increase, so does the complexity of code for the students. Students should be able to follow as well as write these more complicated branching code segments. The switch Statement. The switch also allows for branching, but it has limitations as to what the condition for branching can be. Also, the syntax contains more keywords and is more structured than the if-else. Discussion of the break statement is needed here as the switch will not function properly without the correct use of break between the cases. The Methods equals and equalsignorecase. Since the equality operator cannot be used on objects, we have the equals method. On Strings, we also have the equalsignorecase method when we are concerned with the content of the String, not necessarily that all of the same words are capitalized within the String. The equalsignorecase can be important especially when taking user input. If you ask the user to input a certain letter as a choice, some of them might instinctively make that letter capital. If you are not ignoring case, equals may return false even if the user has pressed the correct key. The and Operator &&. In the section on Boolean Expressions, we introduce the Boolean operators && and. It is important for students to realize when the && operator returns true and when it returns false.

4 The or Operator. The introduction of the operator once again compels students to understand when it will return true and when it will return false in their programs. The Boolean Values are true and false. In Java, the values for the boolean data type are constants that are defined within the system. Therefore, they must always be written in all lower case as true or false. true and false are not Numbers. This point coincides with the last one because in some other languages, true and false can be represented as the numbers 1 and 0. However, in Java this is not the case and trying to use a number where the system expects a boolean value will cause a compiler error. You also can not typecast a number to a boolean or a boolean to a number. Rules for Evaluating Expressions. The precedence and associativity rules for evaluating expressions are given in charts within this chapter. Understanding how to evaluate a boolean expression is as important as how to evaluate the arithmetic expressions in Chapter 1. Syntax for while and do-while Statements. The while and do-while loops are the indefinite loops supported by Java. They also illustrate the differences between an entry-test and an exit-test loop. The for Statement. The for loop is a definite loop or counting loop that is also an entry-test loop. The syntax for the for loop is different from the other two loops and has a loop counter built right into the construct. However, in Java, we can have more than one statement inside the parts of the for-loop separated by commas and we can also leave parts empty, which can create many different results when using a for-loop. Assertion Checking. The assert statement can help you ensure that a particular condition is true at a given time in a program. You can use this feature to make sure that a variable is positive at a given point in the program, for example. You need to turn on assertion checking to make Java execute the assert statements in the program. If at any time, an assertion fails, the program will exit with an error. Tips Placing of Braces. The book introduces its way of placing braces for an if-statement. There are other options, which are presented. Style will vary on what an instructor/programmer wants. There is no correct way to place your braces. However, having braces or not definitely makes a difference in the code. Naming boolean Variables. It is helpful to name boolean variables with names that will indicate what they are holding the values for. Names like isfull, isempty, etc will help distinguish what it is that you are holding the value for and make the code that is written easier for others to read and understand. End of Input Character. This tip is optional and discusses how the user can indicate the end of input to the program. This involves the introduction of control characters in the system and uses the ConsoleIn classes in the example. Therefore, instructors that did not cover ConsoleIn will

5 not be able to cover this point to its entirety, but could discuss how the program will know when the user is done entering input to the program. Repeat N Times Loops. The easiest way to repeat something a definitive number of times is to use the for-loop. The loop counter does not have to be referenced in the loop body, so it can simply just keep track of how many times the loop has been executed. Pitfalls Forgetting a break in a Switch Statement. This is an important pitfall because of the fact that the compiler will not tell you that you have forgotten it. Simply, the program will not execute correctly. Therefore, it is important to show what will happen if the break statements are not properly inserted in the switch statement. Using = Place of ==. Now that we have introduced the notion of equality, one element that is of confusion is that the double equals sign is what actually tests for equality, while the single equals is assignment. This is different than in mathematics and can be confusing for students. In some instances, the confusion of the two may not even cause a compiler error, but once again the program will not run correctly. Using == with Strings. Since Strings are objects, the equality operator does not always give the correct result and should not be used to check for two Strings that contain the same character sequence. The equals method is introduced as the way to achieve the correct answer always to this problem. Strings of Inequalities. Unlike in mathematics, where x < 10 < y is understood, Java will not be able to understand the previous statement. Therefore, it needs to be broken up into two parts, x < 10 && 10 < y. Students who fail to do this will usually receive a compiler error. Extra Semicolon in a for Statement. The extra semicolon at the end of the for loop will not cause a compiler error, but will cause the loop to execute the proper amount of times with an empty loop body. This can also arise with the while loop. However, the do-while needs the semicolon at the end of its condition to work properly. Infinite Loops. It is quite possible and quite common to accidentally write a loop that never ends because the condition on the loop will never become false. These infinite loops will generally cause errors to be generated when the program is run and can be difficult to spot. It is helpful in these cases to use the technique of tracing variables to find the problem. Examples State Income Tax. In this example we see how to use multiway if-else statements with the example of computing how much state income tax one owes. Depending on your level of income, the program gives the amount of tax that should be paid. This problem s solution is given in the text in Display 3.1.

6 Averaging a List of Scores. The second example in this chapter looks at a program that will average a list of scores inputted by the user. This example brings together the input/output from last chapter and the looping that was introduced in this chapter. The code is once again presented in Display 3.8. Programming Projects Answers 1. / Question1.java This program uses the Babylonian algorithm, and keeps looping until the current guess is within 1% of the previous guess value to estimate the square root of a number n. Created: Sat Mar 05, Kenrick 1 / import java.util.scanner; public class Question1 public static void main(string[] args) // Variable declarations Scanner scan = new Scanner(System.in); double guess, previousguess; int n; double r; System.out.println("This program estimate square roots."); System.out.println("Enter an integer to estimate the square root of: "); n = scan.nextint(); // Initial guess guess = (double) n/2; previousguess = n; // Keep looping as long as (oldguess - guess) / old guess is > // The ratio should always be positive since we approach the // square root starting at n/2 and work our way down to the actual square root. while (((previousguess-guess)/previousguess) > 0.01)

7 r = (double) n / guess; previousguess = guess; guess = (guess+r)/2; System.out.println("Current guess: " + guess); System.out.printf("\nThe estimated square root of %d is %6.2f\n", n, guess); // Question1 2. / Question2.java This program simulates 10,000 games of craps. It counts the number of wins and losses and outputs the probability of winning. Created: Sat Mar 05, Kenrick 1 / public class Question2 private static final int NUM_GAMES = 10000; / This is the main method. It loops 10,000 times, each simulate a game of craps. Math.random() is used to get a random number, and we simulate rolling two dice (Math.random() simulates a single die). / public static void main(string[] args) // Variable declarations int numwins = 0; int numlosses = 0; int i; int roll; int point; // Play 10,000 games for (i=0; i<num_games; i++)

8 // Simulate rolling the two dice, with values from 1-6 roll = (int) (Math.random() 6) + (int) (Math.random() 6) + 2; // Check for initial win or loss if ((roll == 7) (roll == 11)) numwins++; else if ((roll==2) (roll==3) (roll==12)) numlosses++; else // Continue rolling until we get the point or 7 point = roll; do roll = (int) (Math.random() 6) + (int) (Math.random() 6) + 2; if (roll==7) numlosses++; else if (roll==point) numwins++; while ((point!= roll) && (roll!= 7)); // Output probability of winning System.out.println("In the simulation, we won " + numwins + " times and lost " + numlosses + " times, " + " for a probability of " + (double) (numwins) / (numwins+numlosses)); // Question2 3. / Question3.java This program estimates the height of a child using the formula: H(male) = (H(mother)13/12 + H(father))/2

9 H(female) = (H(father)12/13 + H(mother))/2 All heights are in inches. A function takes as input parameters the heights in inches and outputs the height in inches. Conversions are made by allowing the user to input the height in feet and inches. Created: Sat Mar 05, Kenrick 1 / import java.util.scanner; public class Question3 / This is the main method. It loops repeatedly until the user stops by not entering "Y" to continue using a do-while loop. Input is accomplished through the Scanner class. / public static void main(string[] args) // Variable declarations int gender; // 0=male, 1=female int mom_feet, mom_inches; int dad_feet, dad_inches; int child_total_inches; String doagain; // Set to "Y" if user wants to try again Scanner scan = new Scanner(System.in); do System.out.println("Enter the gender of your future child. " + "Use 1 for female, 0 for male."); gender = scan.nextint(); System.out.println("Enter the height in feet then the height " + "in inches of the mom."); mom_feet = scan.nextint(); mom_inches = scan.nextint(); System.out.println("Enter the height in feet then the height " + "in inches of the dad."); dad_feet = scan.nextint();

10 dad_inches = scan.nextint(); // Convert input to all inches and get the estimate for the child int mother_height = (mom_feet12)+mom_inches; int father_height = (dad_feet12)+dad_inches; if (gender==0) // Male child formula child_total_inches = ((mother_height 13 / 12) + father_height)/2; else // Female child formula child_total_inches = ((father_height 12 / 13) + mother_height)/2; // Output the estimated height System.out.println("Your future child is estimated to grow to " + child_total_inches / 12 + " feet and " + child_total_inches % 12 + " inches."); System.out.println(); System.out.println("Enter 'Y' to run again, anything else to exit."); scan.nextline(); // Skip newline remaining from nextint doagain = scan.nextline(); while (doagain.equals("y")); // Question3 4. / Question4.java Created: Sun Nov 09 16:00: Modified: Sat Mar , Kenrick Adrienne 2 / import java.util.scanner; import java.text.numberformat;

11 public class Question4 public static void main (String[] args) Scanner keyboard = new Scanner(System.in); System.out.println("Enter the cost of the item " + "in the present as a decimal with" + " no dollar sign:"); double price = keyboard.nextdouble(); System.out.println("Enter the number of years from now" + " you will be purchasing the item:"); int years = keyboard.nextint(); System.out.println("Enter the rate of inflation as " + "a decimal number.\nfor " + "example, enter 5.6 for 5.6%"); double inflation = keyboard.nextdouble() / 100; double newprice = price; for ( int i = 0; i < years; i++ ) newprice = newprice + (newprice inflation); // end of for () NumberFormat moneyformater = NumberFormat.getCurrencyInstance(); System.out.println("in " + years + " years, your item that costs " + moneyformater.format(price) + " now, will cost " + moneyformater.format(newprice)); // end of main () // Question4 5. / Question5.java Created: Sun Nov 09 16:14: Modified: Sat Mar , Kenrick Adrienne 2 /

12 import java.text.numberformat; public class Question5 public static final int STEREO_COST = 1000; public static final double YEARLY_INTEREST = 0.18; public static final double MONTHLY_INTEREST = 0.015; public static final int MONTHLY_PAYMENT = 50; public static void main(string[] args) NumberFormat moneyformater = NumberFormat.getCurrencyInstance(); int monthnumber = 1; double amountremaining = STEREO_COST; double interestaccrued = 0; double diff = 0; double totalinterestpaid = 0; while ( amountremaining > 0.0) //System.out.println("For month number " + monthnumber); /System.out.println("You will pay " + moneyformater.format(monthly_payment));/ interestaccrued = amountremaining MONTHLY_INTEREST; totalinterestpaid = totalinterestpaid + interestaccrued; /System.out.println(moneyFormater.format(interestAccrued) + " will go towards interest.");/ diff = MONTHLY_PAYMENT - interestaccrued; /System.out.println(moneyFormater.format(diff) + " will go towards principle.");/ amountremaining = amountremaining - diff; /System.out.println("You still have " + moneyformater.format(amountremaining) + " to pay.");/ monthnumber++; // end of while () System.out.println("It will take you " + monthnumber + " months to pay off the stereo.");

13 System.out.println("You will have paid " + moneyformater.format(totalinterestpaid) + " in interest."); // Question5 6. / Question6.java Created: Sun Nov 09 16:14: Modified: Sat Mar , Kenrick Adrienne 2 / import java.util.scanner; public class Question6 public static void main(string[] args) Scanner keyboard = new Scanner(System.in); while ( true ) System.out.println("Enter the initial size of the green crud" + " in pounds.\nif you don't want to " + "calculate any more enter -1."); int initialsize = keyboard.nextint(); if ( initialsize == -1) break; // end of if () System.out.println("Enter the number of days: "); int numdays = keyboard.nextint(); int numofrepcycles = numdays / 5; int prevprevgen = 0; int prevgen = initialsize;

14 int finalanswer = initialsize; for ( int i = 0; i < numofrepcycles; i++ ) finalanswer = prevprevgen + prevgen; prevprevgen = prevgen; prevgen = finalanswer; // end of for () System.out.println("The final amount of green crud will be: " + finalanswer + " pounds.\n"); // end of while () // Question6 7. / Question7.java Created: Sun Nov 09 16:14: Modified: Sat Mar , Kenrick Adrienne 2 / import java.util.scanner; public class Question7 public static void main(string[] args) Scanner keyboard = new Scanner(System.in); String line; do System.out.println("Enter the value of X for this calculation."); double x = keyboard.nextdouble(); double sum = 1.0; double temp = 1.0; for ( int n = 1; n <= 10; n++)

15 System.out.print("For n equal to: " + n + ", the result of calculating e^x is: "); for ( int inner = 1; inner <= n; inner++) temp = 1.0; for ( double z = inner; z > 0; z--) temp = temp (x/z); // end of for () sum += temp; // end of for () System.out.println(sum); sum = 1.0; // end of for () System.out.print("For n equal to 50, the result of " + "calculating e^x is: "); for ( int n = 1; n <= 50; n++) temp = 1.0; for ( double z = n; z > 0; z--) temp = temp (x/z); // end of for () sum += temp; // end of for () System.out.println(sum); sum = 1; System.out.print("For n equal to 100, the result of " + "calculating e^x is: "); for ( int n = 1; n <= 100; n++) temp = 1.0; for ( double z = n; z > 0; z--) temp = temp (x/z); // end of for () sum += temp; // end of for () System.out.println(sum);

16 System.out.println("\nEnter Q to quit or Y to go again."); keyboard.nextline(); // Clear buffer line = keyboard.nextline(); while (line.charat(0)!='q' && line.charat(0)!='q'); // end of while () // Question7 8. / Question8.java This program calculates the solution to the cryptarithmetic puzzle TOO + TOO + TOO + TOO = GOOD where each letter represents a single digit with no duplication. It loops over all possible values for each digit, ensures that the digits are unique, computes the sum, and if the equation is satisfied outputs the values for each digit. We must make sure to account for the possibility of carries when adding digits. Created: Thu Mar 22 Kenrick 1 / public class Question8 public static void main(string[] args) // Variable declarations int t, o, g, d; // Loop over all values for "T", "O", "G", and "D" for (t = 0; t <= 9; t++) for (o = 0; o <=9; o++) for (g = 0; g <= 9; g++) for (d = 0; d <= 9; d++) // Ensure uniqueness for each digit if ((t!= o) && (t!= g) && (t!= d) && (o!= g) && (o!= d) && (g!= d))

17 System.out.println(); // Question 8 // Compute rightmost carry and digit int carry0 = (o + o + o + o) / 10; int digit0 = (o + o + o + o) % 10; // Compute second digit from right int carry1 = (carry0 + o + o + o + o) / 10; int digit1 = (carry0 + o + o + o + o) % 10; // Compute third digit from right int carry2 = (carry1 + t + t + t + t) / 10; int digit2 = (carry1 + t + t + t + t) % 10; // Check if equation matches7 if ((carry2 == g) && (digit2 == o) && (digit1 == o) && (digit0 == d)) System.out.println("The values are: T = " + t + " O = " + o + " G = " + g + " D = " + d);

Console Input and Output

Console Input and Output Solutions Manual for Absolute C++ 4th Edition by Walter Savitch Link full download Test bank: https://getbooksolutions.com/download/test-bank-for-absolute-c-4th-edition-by-savitch/ Link full download Solutions

More information

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

L o o p s. for(initializing expression; control expression; step expression) { one or more statements } L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

Full file at

Full file at Chapter 3 Flow of Control Multiple Choice 1) An if selection statement executes if and only if: (a) the Boolean condition evaluates to false. (b) the Boolean condition evaluates to true. (c) the Boolean

More information

Chapter 1 Lab Algorithms, Errors, and Testing

Chapter 1 Lab Algorithms, Errors, and Testing Chapter 1 Lab Algorithms, Errors, and Testing Lab Objectives Be able to write an algorithm Be able to compile a Java program Be able to execute a Java program using the Sun JDK or a Java IDE Be able to

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation. Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

! definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. ! We often use language like Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Absolute C++ 6th Edition Savitch TEST BANK Full download at: https://testbankreal.com/download/absolute-c-6th-edition-savitch-test-bank/

Absolute C++ 6th Edition Savitch TEST BANK Full download at: https://testbankreal.com/download/absolute-c-6th-edition-savitch-test-bank/ Absolute C++ 6th Edition Savitch SOLUTIONS MANUAL Full download at: https://testbankreal.com/download/absolute-c-6th-edition-savitch-solutionsmanual/ Absolute C++ 6th Edition Savitch TEST BANK Full download

More information

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation Program Development Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr The creation of software involves four basic activities: establishing

More information

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

Conditional Programming

Conditional Programming COMP-202 Conditional Programming Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2 Introduction So far,

More information

Program Control Flow

Program Control Flow Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Program Control Flow

Program Control Flow Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

COMP 202. Java in one week

COMP 202. Java in one week COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

More information

Decisions: Logic Java Programming 2 Lesson 7

Decisions: Logic Java Programming 2 Lesson 7 Decisions: Logic Java Programming 2 Lesson 7 In the Java 1 course we learned about if statements, which use booleans (true or false) to make decisions. In this lesson, we'll dig a little deeper and use

More information

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved. Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Over and Over Again GEEN163

Over and Over Again GEEN163 Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Logic & program control part 2: Simple selection structures

Logic & program control part 2: Simple selection structures Logic & program control part 2: Simple selection structures Summary of logical expressions in Java boolean expression means an expression whose value is true or false An expression is any valid combination

More information

CMPT 125: Lecture 4 Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed

More information

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius

More information

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

Flow of Control. Chapter 3

Flow of Control. Chapter 3 Walter Savitch Frank M. Carrano Flow of Control Chapter 3 Outline The if-else statement The Type boolean The switch statement Flow of Control Flow of control is the order in which a program performs actions.

More information

Chapter 17. Iteration The while Statement

Chapter 17. Iteration The while Statement 203 Chapter 17 Iteration Iteration repeats the execution of a sequence of code. Iteration is useful for solving many programming problems. Interation and conditional execution form the basis for algorithm

More information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

Chapter 4: Conditionals and Recursion

Chapter 4: Conditionals and Recursion Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Agenda The modulus operator Random Number Generation Conditional Execution Alternative

More information

Chapter 5 Lab Methods

Chapter 5 Lab Methods Chapter 5 Lab Methods Lab Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation using the javadoc utility Introduction Methods

More information

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

More information

Flow of Control: Loops. Chapter 4

Flow of Control: Loops. Chapter 4 Flow of Control: Loops Chapter 4 Java Loop Statements: Outline The while statement The do-while statement The for Statement Java Loop Statements A portion of a program that repeats a statement or a group

More information

Give one example where you might wish to use a three dimensional array

Give one example where you might wish to use a three dimensional array CS 110: INTRODUCTION TO COMPUTER SCIENCE SAMPLE TEST 3 TIME ALLOWED: 60 MINUTES Student s Name: MAXIMUM MARK 100 NOTE: Unless otherwise stated, the questions are with reference to the Java Programming

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Chapter Goals. Contents LOOPS

Chapter Goals. Contents LOOPS CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

More information

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software. Introduction to Netbeans This document is a brief introduction to writing and compiling a program using the NetBeans Integrated Development Environment (IDE). An IDE is a program that automates and makes

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Algorithms and Conditionals

Algorithms and Conditionals Algorithms and Conditionals CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya,  slide 1 Introduction to Computer Science Shimon Schocken IDC Herzliya Lectures 3-1, 3-2 Control Structures Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 1 Shorthand operators (increment

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

Repetition. Chapter 6

Repetition. Chapter 6 Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

More information

Repetition. Chapter 6

Repetition. Chapter 6 Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

More information

Mr. Monroe s Guide to Mastering Java Syntax

Mr. Monroe s Guide to Mastering Java Syntax Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

Introduction to the Java Basics: Control Flow Statements

Introduction to the Java Basics: Control Flow Statements Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops Chapter 5: Loops and Iteration CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations Suppose that you need to print a string (e.g.,

More information

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.

More information

Control Structures: if and while A C S L E C T U R E 4

Control Structures: if and while A C S L E C T U R E 4 Control Structures: if and while A C S - 1903 L E C T U R E 4 Control structures 3 constructs are essential building blocks for programs Sequences compound statement Decisions if, switch, conditional operator

More information

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

CS1150 Principles of Computer Science Loops (Part II)

CS1150 Principles of Computer Science Loops (Part II) CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Is this an infinite loop? Why (not)?

More information

2.8. Decision Making: Equality and Relational Operators

2.8. Decision Making: Equality and Relational Operators Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

More information

Oct Decision Structures cont d

Oct Decision Structures cont d Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

More information

Flow of Control. Chapter 3

Flow of Control. Chapter 3 Flow of Control Chapter 3 Outline The if-else Stetement The Type boolean The switch statement Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order

More information

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

More information

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) 1 Short Answer (10 Points Each) 1. Write a for loop that will calculate a factorial. Assume that the value n has been input by the user and have the loop create n! and store it in the variable fact. Recall

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

Flow of Control. Chapter 3. Chapter 3 1

Flow of Control. Chapter 3. Chapter 3 1 Flow of Control Chapter 3 Chapter 3 1 Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement chooses between

More information

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18 Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

More information

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

More information

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()

More information

AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

More information

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions: Name: New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case Instructions: KEEP TEST BOOKLET CLOSED UNTIL YOU ARE INSTRUCTED TO BEGIN. This exam is double sided (front

More information

Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

More information

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions: Name: New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case Instructions: KEEP TEST BOOKLET CLOSED UNTIL YOU ARE INSTRUCTED TO BEGIN. This exam is double sided (front

More information

Task #1 The if Statement, Comparing Strings, and Flags

Task #1 The if Statement, Comparing Strings, and Flags Chapter 3 Lab Selection Control Structures Lab Objectives Be able to construct boolean expressions to evaluate a given condition Be able to compare Strings Be able to use a flag Be able to construct if

More information

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4 Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,

More information

Chapter 3. More Flow of Control

Chapter 3. More Flow of Control Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-2 Flow Of Control Flow of control refers to the

More information

Java I/O and Control Structures

Java I/O and Control Structures Java I/O and Control Structures CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying

More information

The action of the program depends on the input We can create this program using an if statement

The action of the program depends on the input We can create this program using an if statement The program asks the user to enter a number If the user enters a number greater than zero, the program displays a message: You entered a number greater than zero Otherwise, the program does nothing The

More information

What methods does the String class provide for ignoring case sensitive situations?

What methods does the String class provide for ignoring case sensitive situations? Nov. 20 What methods does the String class provide for ignoring case sensitive situations? What is a local variable? What is the span of a local variable? How many operands does a conditional operator

More information

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.

More information

Chapter 5 Lab Methods

Chapter 5 Lab Methods Chapter 5 Lab Methods Lab Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation for our Java class using javadoc Introduction

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

CONDITIONAL EXECUTION: PART 2

CONDITIONAL EXECUTION: PART 2 CONDITIONAL EXECUTION: PART 2 yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Review: The if-else statement The switch statement A look

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Introduction to C Programming

Introduction to C Programming 1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times Iteration: Intro Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times 2. Posttest Condition follows body Iterates 1+ times 1 Iteration: While Loops Pretest loop Most general loop construct

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Chapter 3 Lab Decision Structures

Chapter 3 Lab Decision Structures Chapter 3 Lab Decision Structures Lab Objectives Be able to construct boolean expressions to evaluate a given condition Be able to compare String objects Be able to use a flag Be able to construct if and

More information

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 Java Foundations Introduction to Program Design and Data Structures 4th Edition Lewis TEST BANK Full download at : https://testbankreal.com/download/java-foundations-introduction-toprogram-design-and-data-structures-4th-edition-lewis-test-bank/

More information

Chapter 3. Ch 1 Introduction to Computers and Java. Selections

Chapter 3. Ch 1 Introduction to Computers and Java. Selections Chapter 3 Ch 1 Introduction to Computers and Java Selections 1 The if-else Statement 2 Flow Chart Deconstructed Decision: Make a choice Start Terminator: Show start/stop points T boolean expression F true

More information