Full file at

Similar documents
Loops. CSE 114, Computer Science 1 Stony Brook University

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

In this chapter, you will:

Building Java Programs

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

Building Java Programs

Java Coding 3. Over & over again!

STUDENT LESSON A12 Iterations

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Full file at

Controls Structure for Repetition

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Repetition, Looping. While Loop

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

Flow of Control. Chapter 3

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

CMPT 125: Lecture 4 Conditionals and Loops

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Full file at

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved.

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Chapter 3. Selections

Programming with Java

Introduction to the Java Basics: Control Flow Statements

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

Type boolean. Building Java Programs. Recap: Type boolean. "Short-circuit" evaluation. De Morgan's Law. Boolean practice questions.

Conditional Execution

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Midterm Examination (MTA)

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

CompSci 125 Lecture 11

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

! 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

204111: Computer and Programming

Repetition. Chapter 6

Repetition. Chapter 6

Repetition CSC 121 Fall 2014 Howard Rosenthal

Java Basic Programming Constructs

Flow of Control. Chapter 3

Introduction. C provides two styles of flow control:

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Combined Assignment Operators. Flow of Control. Increment Decrement Operators. Operators Precedence (Highest to Lowest) Slide Set 05: Java Loops

Course Outline. Introduction to java

CS 106 Introduction to Computer Science I

Loops. GEEN163 Introduction to Computer Programming

Chapter 4: Control structures. Repetition

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Topics. Chapter 5. Equality Operators

REPETITION CONTROL STRUCTURE LOGO

Chapter 4: Control Structures I

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

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

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

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Problem Solving With Loops

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

5. Control Statements

Lesson 7 Part 2 Flags

Handout 4 Conditionals. Boolean Expressions.

Chapter 4: Control structures

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

St. Edmund Preparatory High School Brooklyn, NY

Operators. Java operators are classified into three categories:

Example: Monte Carlo Simulation 1

Program Control Flow

Program Control Flow

PROGRAMMING FUNDAMENTALS

Chapter 2. Elementary Programming

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

CEN 414 Java Programming

Oct Decision Structures cont d

ITERATION WEEK 4: EXMAPLES IN CLASS

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

2.8. Decision Making: Equality and Relational Operators

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

Introduction to Programming Using Java (98-388)

Flow of Control: Loops. Chapter 4

JAVA OPERATORS GENERAL

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

Section 2.2 Your First Program in Java: Printing a Line of Text

Flow of Control. Chapter 3. Chapter 3 1

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

Introduction to Computer Programming

Introduction to Java & Fundamental Data Types

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Chapter Goals. Chapter 5 - Iteration. Calculating the Growth of an Investment

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

What two elements are usually present for calculating a total of a series of numbers?

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

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Transcription:

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 condition is short-circuited. (d) none of the above. Answer: B 2) A compound statement is enclosed between: (a) [ ] (b) (c) ( ) (d) < > Answer: B 3) A multi-way if- statement (a) allows you to choose one course of action. (b) always executes the statement. (c) allows you to choose among alternative courses of action. (d) executes all Boolean conditions that evaluate to true. Answer: C 4) The controlling expression for a switch statement includes all of the following types except: (a) char (b) int (c) byte (d) double Answer: D 1

2 Walter Savitch Absolute Java 3/e: Chapter 3 Test Bank 5) To compare two strings lexicographically the String method should be used. (a) equals (b) equalsignorecase (c) compareto (d) == Answer: C 6) When using a compound Boolean expression joined by an && (AND) in an if statement: (a) Both expressions must evaluate to true for the statement to execute. (b) The first expression must evaluate to true and the second expression must evaluate to false for the statement to execute. (c) The first expression must evaluate to false and the second expression must evaluate to true for the statement to execute. (d) Both expressions must evaluate to false for the statement to execute. Answer: A 7) The OR operator in Java is represented by: (a)! (b) && (c) (d) None of the above Answer: C 8) The negation operator in Java is represented by: (a)! (b) && (c) (d) None of the above Answer: A 9) The operator has the highest precedence. (a) * (b) dot (c) += (d) decrement Answer: B 10) The association of operands with operators is called. (a) assignment (b) precedence (c) binding (d) lexicographic ordering Answer: C

Chapter 3 Flow of Control 3 11) The looping mechanism that always executes at least once is the statement. (a) if (b) do while (c) while (d) for Answer: B 12) A mixture of programming language and human language is known as: (a) Algorithms (b) Recipes (c) Directions (d) Pseudocode Answer: D 13) When the number of repetitions are known in advance, you should use a statement. (a) while (b) do while (c) for (d) None of the above Answer: C 14) A statement terminates the current iteration of a loop. (a) Break (b) Continue (c) Switch (d) Assert Answer: B 15) Common loop errors are: (a) Off-by-one (b) Infinite loops (c) Both a and b (d) None of the above Answer: C 16) To terminate a program, use the Java statement: (a) System.quit(0); (b) System.end(0); (c) System.abort(0); (d) System.exit(0); Answer: D

4 Walter Savitch Absolute Java 3/e: Chapter 3 Test Bank 17) Good debugging techniques include: (a) Inserting output statements in your program. (b) Tracing variables (c) Using an IDE debugger (d) All of the above Answer: D True/False 1) An if- statement chooses between two alternative statements based on the value of a Boolean expression. 2) You may omit the part of an if- statement if no alternative action is required. 3) In a switch statement, the choice of which branch to execute is determined by an expression given in parentheses after the keyword switch. 4) In a switch statement, the default case is always executed. Answer: False 5) Not including the break statements within a switch statement results in a syntax error. Answer: False 6) The equality operator (==) may be used to test if two string objects contain the same value. Answer: False 7) Boolean expressions are used to control branch and loop statements. 8) The for statement, do while statement and while statement are examples of branching mechanisms. Answer: False 9) When choosing a sentinel value, you should choose a value that would never be encountered in the input of the program. 10) An algorithm is a step-by-step method of solution.

Chapter 3 Flow of Control 5 11) The three expressions at the start of a for statement are separated by two commas. Answer: False 12) An empty statement is defined as a loop that runs forever. Answer: False Short Answer/Essay 1) What output will be produced by the following code? public class SelectionStatements public static void main(string[] args) int number = 24; if(number % 2 == 0) System.out.print("The condition evaluated to true!"); System.out.print("The condition evaluated to false!"); Answer: The condition evaluated to true! 2) What would be the output of the code in #1 if number was originally initialized to 25? Answer: The condition evaluated to false!

6 Walter Savitch Absolute Java 3/e: Chapter 3 Test Bank 3) Write a multi-way if- statement that evaluates a persons weight on the following criteria: A weight less than 115 pounds, output: Eat 5 banana splits! A weight between 116 pounds and 130 pounds, output: Eat a banana split! A weight between 131 pounds and 200 pounds, output: Perfect! A weight greater than 200 pounds, output: Plenty of banana splits have been consumed! Answer: if(weight <= 115) System.out.println("Eat 5 banana splits!"); if(weight <= 130) System.out.println("Eat a banana split!"); if(weight <=200) System.out.println("Perfect!"); System.out.println("Plenty of banana splits have been consumed!"); 4) Name and describe three types of branching mechanisms and give an example of each. Answer: Three types of branching mechanisms include the if- statement, the multi-way if- statement, and the switch statement. An if- statement chooses between two alternative statements based on the value of a Boolean expression. If you only need to perform an action if a certain condition is true, then the part of an if- statement can be omitted. A multi-way if statement allows several conditions to be evaluated. The first condition that evaluates to true, is the branch that is executed. The switch statement is another multi-selection branching mechanism. A switch evaluates a controlling expression and executes the statements in the matching case label. If example: if ( taxableincome > 30000) taxrate =.135; taxrate =.075; Multi-way if- example: If(taxableIncome < 10000) taxrate =.0425; if(taxableincome < 30000) taxrate =.075; taxrate =.135;

Chapter 3 Flow of Control 7 Switch example: char mychar = b ; switch(mychar) case a : System.out.println( It is an A ); break; case b : case default: System.out.println( It is a B ); break; System.out.println( Default case ); break; 5) Write an if- statement to compute the amount of shipping due on an online sale. If the cost of the purchase is less than $20, the shipping cost is $5.99. If the cost of the purchase over $20 and at most $65, the shipping cost is $10.99. If the cost of the purchase is over $65, the shipping cost is $15.99. Answer: if(costofpurchase < 20) shippingcost = 5.99; if((costofpurchase > 20)&&(costOfPurchase <= 65)) shippingcost = 10.99; shippingcost = 15.99; 6) Evaluate the Boolean equation:!( ( 6 < 5) && (4 < 3))

8 Walter Savitch Absolute Java 3/e: Chapter 3 Test Bank 7) What is short-circuit evaluation of Boolean expressions? Answer: Short-circuit evaluation is a mechanism in Java that allows the early termination of the evaluation of a compound Boolean expression. This occurs when two Boolean expressions are joined by the && operator when the first expression evaluates to false. The evaluation short-circuits because no matter what the value of the second expression is, the expression will evaluate to false. When two Boolean expressions are joined by the operator, if the first expression evaluates to true, then the evaluation will short circuit because the expression will always evaluate to true no matter what the second expression evaluates to. 8) Discuss the rules Java follows when evaluating expressions. Answer: First, Java binds operands with operators by fully parenthesizes the expression using precedence and associativity rules. Next, Java evaluates expressions from left to right. Finally, if an operator is waiting for other operands to be evaluated, then that operator is evaluated as soon as its operands have been evaluated. 9) Write Java code that uses a do while loop that prints even numbers from 2 through 10. Answer: int evennumber = 2; do System.out.println(evenNumber); evennumber += 2; while(evennumber <= 10); 10) Write Java code that uses a while loop to print even numbers from 2 through 10. Answer: int evennumber = 2; while(evennumber <= 10) System.out.println(evenNumber);

Chapter 3 Flow of Control 9 evennumber += 2; 11) What is a sentinel value and how is it used? Answer: A sentinel value is a value that should never be encountered in the input of the program. It is used to control looping mechanisms when the number of repetitions is unknown. When the sentinel value is encountered, the loop terminates. A sentinel value is commonly used with while and do.while statements. 12) Write Java code that uses a for statement to sum the numbers from 1 through 50. Display the total sum to the console. Answer: int sum = 0; for(int i=1; i <= 50; i++) sum += i; System.out.println("The total is: " + sum); 13) What is the output of the following code segment? public static void main(string[] args) int x = 5; System.out.println("The value of x is:" + x); while(x > 0) x++;

10 Walter Savitch Absolute Java 3/e: Chapter 3 Test Bank System.out.println("The value of x is:" + x); Answer: The value of x is 5. The program then enters an infinite loop because the value of x is always greater than 0. 14) Discuss the differences between the break and the continue statements when used in looping mechanisms. Answer: When the break statement is encountered within a looping mechanism, the loop immediately terminates. When the continue statement is encountered within a looping mechanism, the current iteration is terminated, and execution continues with the next iteration of the loop. 15) Write a complete Java program that prompts the user for a series of numbers to determine the smallest value entered. Before the program terminates, display the smallest value. Answer: import java.util.scanner; public class FindMin public static void main(string[] args) Scanner keyboard = new Scanner(System.in); int smallest = 9999999; String userinput;

Chapter 3 Flow of Control 11 boolean quit = false; System.out.println("This program finds the smallest number" + " in a series of numbers"); System.out.println("When you want to exit, type Q"); while(quit!= true) System.out.print("Enter a number: "); userinput = keyboard.next(); if(userinput.equals("q") userinput.equals("q")) quit = true; int usernumber = Integer.parseInt(userInput);

12 Walter Savitch Absolute Java 3/e: Chapter 3 Test Bank if(usernumber < smallest) smallest = usernumber; System.out.println("The smallest number is " + smallest); System.exit(0); 16) Write a complete Java program that uses a for loop to compute the sum of the even numbers and the sum of the odd numbers between 1 and 25. public class sumevenodd public static void main(string[] args) int evensum = 0; int oddsum = 0; //loop through the numbers for(int i=1; i <= 25; i++) if(i % 2 == 0)

Chapter 3 Flow of Control 13 //even number evensum += i; oddsum += i; //Output the results System.out.println("Even sum = " + evensum); System.out.println("Odd sum = " + oddsum);