Maximization and Minimization Problems. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Size: px
Start display at page:

Download "Maximization and Minimization Problems. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington"

Transcription

1 Maximization and Minimization Problems CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1

2 Maximization Problems Given a set of data, we want to find the object for which some criterion is maximized. Examples: Given a string, find the character that occurs the most times. Given grade information for many students, find the student with the highest GPA. Given fuel consumption information for many car models, find the car model with the highest mileage per gallon. 2

3 Minimization Problems Similarly, in many other cases, given a set of data, we want to find the object for which some criterion is minimized. Examples: Given information about many flights from DFW to Paris, find the cheapest ticket (minimize the price). Given temperature information for multiple locations, find the location with the lowest temperature. 3

4 An Example Maximization/Minimization Problem Let s solve a specific maximization problem: Given a string, find the character that occurs the most consecutive times in that string. More specifically: Let s write a function maxconsecutivechar that takes a string as an argument, and returns the character that occurs the most consecutive times in that string. For example: maxconsecutivechar("hello") returns 'l'. maxconsecutivechar("abcccababab") returns 'C'. 4

5 Main Function public static void main(string[] args) Scanner in = new Scanner(System.in); while (true) System.out.printf("Please enter some text, or q to quit: "); String text = in.nextline(); if (text.tolowercase().equals("q")) break; if (text.length() == 0) continue; char c = maxconsecutivechar(text); System.out.printf("Result: %c.\n\n", c); System.out.println("Exiting..."); 5

6 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Note: this function calls an auxiliary function, called countconsecutive, defined in the next slide. 6

7 countconsecutive Function public static int countconsecutive(string str, int position) int counter = 0; for (int i = position; i < str.length(); i++) char c1 = str.charat(position); char c2 = str.charat(i); if (c1 == c2) counter++; else break; return counter; 7

8 A Closer Look at maxconsecutivechar Function maxconsecutivechar is the function that solves the maximization problem. This function follows some specific steps, which are common to all maximization/minimization problems. Let's look at these steps, one by one. 8

9 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Step 1: initialize a variable that will keep track of the max value that we find as we go through the data. 9

10 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Step 2: initialize a variable that will keep track of the max object, i.e., the object corresponding to the max value that we find as we go through the data. 10

11 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Step 3: do a loop, to go through all our data. 11

12 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Step 4: measure the current value. 12

13 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Step 5: if the current value is larger than the max value we have seen so far, update the variables for BOTH the max value AND the max object. 13

14 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Step 5a: if the current value is the largest value we have seen so far, update the max value variable. 14

15 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Step 5b: if the current value is the largest value we have seen so far, update the max object variable. 15

16 maxconsecutivechar Function public static char maxconsecutivechar(string str) int max_counter = 0; char max_char = '1'; for (int i = 0; i < str.length(); i++) int times = countconsecutive(str, i); if (times > max_counter) max_counter = times; max_char = str.charat(i); return max_char; Step 6: AFTER we have searched all the data, return the variable for the max object (may or may not be the max 16 value itself, depending on the problem).

17 Maximization: Summary of All Steps Step 1: initialize a variable that will keep track of the max value that we find as we go through the data. Step 2: initialize a variable that will keep track of the max object, i.e., the object corresponding to the max value that we find as we go through the data. Step 3: do a loop, to go through all our data. Step 4: measure the current value. Step 5: if the current value is larger than the max value we have seen so far, update the variables for BOTH the max value AND the max object. Step 6: AFTER we have searched all the data, return the variable for the max object (may or may not be the max value itself, depending on the problem). 17

18 Maximization vs. Minimization For minimization problems, you follow the exact same steps. You just need to make obvious changes, since now you are searching for the minimum value, not the maximum value. 18

19 Minimization: Summary of All Steps Step 1: initialize a variable that will keep track of the min value that we find as we go through the data. Step 2: initialize a variable that will keep track of the min object, i.e., the object corresponding to the min value that we find as we go through the data. Step 3: do a loop, to go through all our data. Step 4: measure the current value. Step 5: if the current value is smaller than the min value we have seen so far, update the variables for BOTH the min value AND the min object. Step 6: AFTER we have searched all the data, return the variable for the min object (may or may not be the min value itself, depending on the problem). 19

20 A Closer Look at Step 1 Step 1: initialize a variable that will keep track of the max value that we find as we go through the data. What is a good initial value? You have to choose that value very carefully, otherwise your solution may not work. 20

21 A Closer Look at Step 1 Step 1: initialize a variable that will keep track of the max value that we find as we go through the data. What is a good initial value? You have to choose that value very carefully, otherwise your solution may not work. You must pick an initial value that is guaranteed to be lower than any actual value that you find in your data. The right value depends on the problem. For the max-consecutive problem, 0 is a good choice. No character will appear fewer than 0 consecutive times. -1 (or any other negative number) would also be a good choice. 21

22 A Closer Look at Step 2 Step 2: initialize a variable that will keep track of the max object, i.e., the object corresponding to the max value that we find as we go through the data. What is a good initial value? 22

23 A Closer Look at Step 2 Step 2: initialize a variable that will keep track of the max object, i.e., the object corresponding to the max value that we find as we go through the data. What is a good initial value? As long as you did step 1 right, the initial value for step 2 does not matter. This initial value will be replaced immediately, when you start looking at the data. Special case: what if you have no data? Make sure that your code does something reasonable in that case. In our max-consecutive code, the main function prevents that case (see next slide). 23

24 Checking for Empty Data public static void main(string[] args) Scanner in = new Scanner(System.in); while (true) System.out.printf("Please enter some text, or q to quit: "); String text = in.nextline(); if (text.tolowercase().equals("q")) break; if (text.length() == 0) continue; char c = maxconsecutivechar(text); System.out.printf("Result: %c.\n\n", c); System.out.println("Exiting..."); If the data is empty, we do not call maxconsecutivechar. 24

Common Mistakes with Functions. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Common Mistakes with Functions. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Common Mistakes with Functions CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Common Mistakes with Functions Printing instead of returning. Returning

More information

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first

More information

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first

More information

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first

More information

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8 CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8 Hopefully the Programming Assignment #1 released by tomorrow REVIEW The switch statement is an alternative way of writing what? How do you end a case in

More information

Introduction to Programming (Java) 4/12

Introduction to Programming (Java) 4/12 Introduction to Programming (Java) 4/12 Michal Krátký Department of Computer Science Technical University of Ostrava Introduction to Programming (Java) 2008/2009 c 2006 2008 Michal Krátký Introduction

More information

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington Arrays and Array Lists CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington 1 Motivation Current limitation: We cannot record multiple

More information

Introduction to Software Development (ISD) Week 3

Introduction to Software Development (ISD) Week 3 Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process

More information

Methods (Functions) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Methods (Functions) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Methods (Functions) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 What Is a Method? A method is a mechanism for allowing a piece of code to be

More information

Array Lists. CSE 1310 Introduction to Computers and Programming University of Texas at Arlington. Last modified: 4/17/18

Array Lists. CSE 1310 Introduction to Computers and Programming University of Texas at Arlington. Last modified: 4/17/18 Array Lists CSE 1310 Introduction to Computers and Programming University of Texas at Arlington Last modified: 4/17/18 1 DEPARTAMENTAL FINAL EXAM Monday, DEC 10, 5:30pm-8pm rooms will be determined 2 Fixed

More information

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as Control structures in Java are statements that contain statements. In particular, control structures can contain control structures. You've already seen several examples of if statements inside loops,

More information

Question: Total Points: Score:

Question: Total Points: Score: CS 170 Exam 1 Section 000 Spring 2014 Name (print):. Instructions Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

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

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Loop - 3 & Class. Cheng, Wei COMP May 22, Title

Loop - 3 & Class. Cheng, Wei COMP May 22, Title Loop - 3 & Class Cheng, Wei COMP110-001 May 22, 2014 Title How many iterations? for (count = 1; count < 10; count++) Loop 9 times for (count = 1; count

More information

Chapter 7 User-Defined Methods. Chapter Objectives

Chapter 7 User-Defined Methods. Chapter Objectives Chapter 7 User-Defined Methods Chapter Objectives Understand how methods are used in Java programming Learn about standard (predefined) methods and discover how to use them in a program Learn about user-defined

More information

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions: CS 170 Exam 2 Version: A Fall 2015 Name (as in OPUS) (print): Section: Seat Assignment: Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do

More information

Formatted Output (printf) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Formatted Output (printf) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Formatted Output (printf) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Formatted Printing - References Java API: https://docs.oracle.com/javase/7/docs/api/java/util/formatter.html#syntax

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

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

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue General Loops in Java Look at other loop constructions Very common while loop: do a loop a fixed number of times (MAX in the example) int

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

Chapter 6. Repetition. Asserting Java. Rick Mercer

Chapter 6. Repetition. Asserting Java. Rick Mercer Chapter 6 Repetition Asserting Java Rick Mercer Algorithmic Pattern: The Determinate loop We often need to perform some action a specific number of times: Produce 89 paychecks. Count down to 0 (take 1

More information

Name CIS 201 Midterm II: Chapters 1-8

Name CIS 201 Midterm II: Chapters 1-8 Name CIS 201 Midterm II: Chapters 1-8 December 15, 2010 Directions: This is a closed book, closed notes midterm. Place your answers in the space provided. The point value for each question is indicated.

More information

a data type is Types

a data type is Types Pointers Class 2 a data type is Types Types a data type is a set of values a set of operations defined on those values in C++ (and most languages) there are two flavors of types primitive or fundamental

More information

Variables, Types, Operations on Numbers

Variables, Types, Operations on Numbers Variables, Types, Operations on Numbers CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Updated 9/6/16 1 Summary Variable declaration, initialization,

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

CSE 114 Computer Science I

CSE 114 Computer Science I CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

Conditional Execution

Conditional Execution Unit 3, Part 3 Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Simple Conditional Execution in Java if () { else {

More information

Array. Array Declaration:

Array. Array Declaration: Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and

More information

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods Chapter 7: User-Defined Methods Java Programming: Program Design Including Data Structures Chapter Objectives Understand how methods are used in Java programming Learn about standard (predefined) methods

More information

Example Program. public class ComputeArea {

Example Program. public class ComputeArea { COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for

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

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks: كلية الحاسبات وتقنية المعلوما Exam 2 Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: November 22, 2015 Student Name: Student ID: Total Marks: 40 Obtained Marks: Instructions: Do not open this

More information

1 Short Answer (5 Points Each)

1 Short Answer (5 Points Each) 1 Short Answer (5 Points Each) 1. What are the three types of programming errors? Briefly describe each of them. Syntax Error: An error in the program code due to misuse of the programming language. Run-time

More information

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

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

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1 UNIVERSITY OF EAST ANGLIA School of Computing Sciences Main Series UG Examination 2017-18 PROGRAMMING 1 CMP-4008Y Time allowed: 2 hours Answer FOUR questions. All questions carry equal weight. Notes are

More information

Chapter 4: Control Structures I

Chapter 4: Control Structures I Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore

More information

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8 Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How

More information

Handout 4 Conditionals. Boolean Expressions.

Handout 4 Conditionals. Boolean Expressions. Handout 4 cs180 - Programming Fundamentals Fall 17 Page 1 of 8 Handout 4 Conditionals. Boolean Expressions. Example Problem. Write a program that will calculate and print bills for the city power company.

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]

More information

Part (II): In the body method main : Write the call to method formatname and have the return value stored in the variable formatted.

Part (II): In the body method main : Write the call to method formatname and have the return value stored in the variable formatted. CPSC 233 Midterm Review: Winter 2013 Written questions: Question 1 Refer to the code in class MyFormatter and class Driver public class MyFormatter { private String first; private String last; private

More information

Binary and Hexadecimal Numbers. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Binary and Hexadecimal Numbers. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Binary and Hexadecimal Numbers CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Decimal Numbers A decimal number is an integer written the way we

More information

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions: Boolean Expressions Now we have the ability to read in some information, calculate some formulas and display the information to the user in a nice format. However, the real power of computer programs lies

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Arrays A data structure for a collection of data that is all of the same data type. The data type can be

More information

Darrell Bethea May 20, 2011

Darrell Bethea May 20, 2011 Darrell Bethea May 20, 2011 Program 2 due Monday Midterm in one week Moved to SN014 (next door) Will cover up to yesterday (Ch. 1-4) Future office hours moved to FB331 2 3 Briefly go over Strings and Loops

More information

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Activity 4: Methods. Content Learning Objectives. Process Skill Goals Activity 4: Methods Java programs are organized into classes, each of which has one or more methods, each of which has one or more statements. Writing methods allows you to break down a complex program

More information

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

Chapter Goals. Chapter 5 - Iteration. Calculating the Growth of an Investment Chapter Goals To be able to program loops with the while and for statements To avoid infinite loops and off-by-one errors To be able to use common loop algorithms To understand nested loops To implement

More information

CS141 Programming Assignment #5

CS141 Programming Assignment #5 CS141 Programming Assignment #5 Due Wednesday, Nov 16th. 1) Write a class that asks the user for the day number (0 to 6) and prints the day name (Saturday to Friday) using switch statement. Solution 1:

More information

CSE142 Sample Midterm Spring Name UW NetId (e.g. whitab) Section (e.g., AA) TA

CSE142 Sample Midterm Spring Name UW NetId (e.g. whitab) Section (e.g., AA) TA CSE142 Sample Midterm Spring 2018 Name UW NetId (e.g. whitab) Section (e.g., AA) TA This exam is divided into nine questions with the following points: # Problem Area Points Score ---------------------------------------------

More information

SELECTION. (Chapter 2)

SELECTION. (Chapter 2) SELECTION (Chapter 2) Selection Very often you will want your programs to make choices among different groups of instructions For example, a program processing requests for airline tickets could have the

More information

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003 1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 7, 2003 Name: Email Address: TA: Section: You have 90 minutes to complete this exam. For coding questions, you do not need to

More information

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007 Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2007 Final Examination Question Max

More information

Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types:

Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types: Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types: int, short, byte, long, float, double, boolean, char The data

More information

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

Section 002 Spring CS 170 Exam 1. Name (print): Instructions: CS 170 Exam 1 Section 002 Spring 2015 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

More information

1 Short Answer (15 Points Each)

1 Short Answer (15 Points Each) COSC 7 Exam # Solutions Spring 08 Short Answer (5 Points Each). Write a method called RollCount that takes in two integer parameters rolls and target. The method should simulate the rolling of two die,

More information

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by: Menu Driven Systems While loops, menus and the switch statement Produced by: Mairead Meagher Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list while loops recap

More information

CSC142, Computer Science II, Project 5 (2 nd submission)

CSC142, Computer Science II, Project 5 (2 nd submission) CSC142, Computer Science II, Project 5 (2 nd submission) Due via D2L. Late programs are not acceptable. Evaluation: Your score is given only when the program follows the given template and can fully support

More information

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other

More information

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 Question One: Choose the correct answer and write it on the external answer booklet. 1. Java is. a. case

More information

CSIS 10A Assignment 9 Solutions

CSIS 10A Assignment 9 Solutions CSIS 10A Assignment 9 Solutions Read: Chapter 9 Choose and complete any 10 points from the problems below, which are all included in the download file on the website. Use BlueJ to complete the assignment,

More information

www.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some

More information

Chapter 6. Repetition. Asserting Java. Rick Mercer

Chapter 6. Repetition. Asserting Java. Rick Mercer Chapter 6 Repetition Asserting Java Rick Mercer Algorithmic Pattern: The Determinate loop We often need to perform some action a specific number of times: Produce 89 paychecks. Count down to 0 (take 1

More information

Java Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved.

Java Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved. Java Programming String Processing 1 Copyright 2013, Oracle and/or its affiliates. All rights Overview This lesson covers the following topics: Read, search, and parse Strings Use StringBuilder to create

More information

Top-Down Program Development

Top-Down Program Development Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable

More information

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use: CSE 20 SAMPLE FINAL Version A Time: 180 minutes Name The following precedence table is provided for your use: Precedence of Operators ( ) - (unary),!, ++, -- *, /, % +, - (binary) = = =,!= &&

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

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

Name: Checked: Preparation: Response time experiment accessing the system clock

Name: Checked: Preparation: Response time experiment accessing the system clock Lab 6 Name: Checked: Objectives: Practice using the conditional operator; switch statements; do and for loops. Learn how to implement a simple experimental setup to measure response times using System.currentTimeMillis()

More information

MIDTERM REVIEW. midterminformation.htm

MIDTERM REVIEW.   midterminformation.htm MIDTERM REVIEW http://pages.cpsc.ucalgary.ca/~tamj/233/exams/ midterminformation.htm 1 REMINDER Midterm Time: 7:00pm - 8:15pm on Friday, Mar 1, 2013 Location: ST 148 Cover everything up to the last lecture

More information

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

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018 Motivating Examples (1.1) Selections EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG 1 import java.util.scanner; 2 public class ComputeArea { 3 public static void main(string[] args)

More information

Strings. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Strings. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Strings CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Summary String type Concatenation: +, += Escape sequences Substring Substring vs char my_str.length()

More information

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays Chapter 5 Arrays Learning Objectives Introduction to Arrays Declaring and referencing arrays For-loops and arrays Arrays in memory Arrays in Functions Arrays as function arguments, return values Programming

More information

Question: Total Points: Score:

Question: Total Points: Score: CS 170 Exam 1 Section 001 Fall 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

More information

/** * Utility class to support string reassembly from fragments. * Emily McIntyre * <pre> * * OVERLAPS ( * s1: string of

/** * Utility class to support string reassembly from fragments. * Emily McIntyre * <pre> * * OVERLAPS ( * s1: string of Utility class to support string reassembly from fragments. @author Emily McIntyre @mathdefinitions OVERLAPS ( s1: string of character, s2: string of character, k: integer ) : boolean is 0

More information

Name: Lirong TAN 1. (15 pts) (a) Define what is a shortest s-t path in a weighted, connected graph G.

Name: Lirong TAN 1. (15 pts) (a) Define what is a shortest s-t path in a weighted, connected graph G. 1. (15 pts) (a) Define what is a shortest s-t path in a weighted, connected graph G. A shortest s-t path is a path from vertex to vertex, whose sum of edge weights is minimized. (b) Give the pseudocode

More information

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

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website: 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

Activity 9: Object-Oriented

Activity 9: Object-Oriented Activity 9: Object-Oriented Internally, the library class java.lang.string stores an array of characters. It also provides a variety of useful methods for comparing, manipulating, and searching text in

More information

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

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Selections EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes The Boolean Data Type if Statement Compound vs. Primitive Statement Common Errors

More information

CSE 113. Announcements

CSE 113. Announcements CSE 113 September 20, 2010 Lab 3 posted Announcements Grades for all labs are still not being computed because of problem with Web-CAT s grading module hopefully we will get to a resolution this week Exam

More information

CSE 143 Sample Midterm Exam #4

CSE 143 Sample Midterm Exam #4 CSE 143 Sample Midterm Exam #4 (based on Summer 2009's midterm; thanks to Alyssa Harding) 1. ArrayList Mystery. Consider the following method: public static void mystery4(arraylist list) { for

More information

Following is the general form of a typical decision making structure found in most of the programming languages:

Following is the general form of a typical decision making structure found in most of the programming languages: Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined

More information

( &% class MyClass { }

( &% class MyClass { } Recall! $! "" # ' ' )' %&! ( &% class MyClass { $ Individual things that differentiate one object from another Determine the appearance, state or qualities of objects Represents any variables needed for

More information

There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:

There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do: Project MindNumber Collaboration: Solo. Complete this project by yourself with optional help from section leaders. Do not work with anyone else, do not copy any code directly, do not copy code indirectly

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

ITERATION WEEK 4: EXMAPLES IN CLASS

ITERATION WEEK 4: EXMAPLES IN CLASS Monday Section 2 import java.util.scanner; public class W4MSection2 { ITERATION WEEK 4: EXMAPLES IN CLASS public static void main(string[] args) { Scanner input1 = new Scanner (System.in); int CircleCenterX

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

McGill University School of Computer Science COMP-202A Introduction to Computing 1

McGill University School of Computer Science COMP-202A Introduction to Computing 1 McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif

More information

In this chapter, you will:

In this chapter, you will: Java Programming: Guided Learning with Early Objects Chapter 4 Control Structures I: Selection In this chapter, you will: Make decisions with the if and if else structures Use compound statements in an

More information

Practice Midterm 2 CMPS 12A Fall 2017

Practice Midterm 2 CMPS 12A Fall 2017 1.) Determine the output of the following program. public class Question1{ Car x = new Car("gray", 100000); Car y = new Car("red", 125000); Car z = new Car("blue", 150000); x = y; roadtrip(x); z = x; System.out.println(z.mileage);

More information

1. Code Trace: 2. Program Logic (0.5 each) X <= y y > z x == 1 A S N S N S A A N S S S S A S POINT A POINT B POINT C POINT D POINT E

1. Code Trace: 2. Program Logic (0.5 each) X <= y y > z x == 1 A S N S N S A A N S S S S A S POINT A POINT B POINT C POINT D POINT E CS312 Fall 2017 Exam 2 Solution and Grading Criteria. Grading acronyms: AIOBE - Array Index out of Bounds Exception may occur BOD - Benefit of the Doubt. Not certain code works, but, can't prove otherwise

More information

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

while (/* array size less than 1*/){ System.out.print(Number of students is invalid. Enter + number of students: ); /* read array size again */ import java.util.scanner; public class CourseManager1 { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter number of students: "); /* read the number

More information

Question: Total Points: Score:

Question: Total Points: Score: CS 170 Exam 1 Section 000 Spring 2015 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

More information

Lab 6. Name: Checked:

Lab 6. Name: Checked: Lab 6 Name: Checked: Objectives: Practice using the conditional operator; switch statements; do and for loops. Learn how to implement a simple experimental setup to measure response times using System.currentTimeMillis()

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

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4) Loops! Flow of Control: Loops (Savitch, Chapter 4) TOPICS while Loops do while Loops for Loops break Statement continue Statement CS 160, Fall Semester 2014 2 An Example while Loop Step- by- step int count

More information