Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Size: px
Start display at page:

Download "Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals"

Transcription

1 Arrays Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

2 Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = days were above average. 2

3 Why the problem is hard We need each input value twice: to compute the average (a cumulative sum) to count how many were above average We could read each value into a variable... but we: don't know how many days are needed until the program runs don't know how many variables to declare We need a way to declare many variables in one step. Luckily, Java has a built-in structure, the array, that makes this problem very easy to solve. 3

4 Arrays array: object that stores many values of the same type. element: One value in an array. index: A 0-based integer to access an element from an array. index value element 0 element 4 element 9 4

5 Array declaration type[] name = new type[length]; Example: int[] numbers = new int[10]; index value

6 Array declaration, cont. The length can be any integer expression. int x = 2 * 3 + 1; int[] data = new int[x % 5 + 2]; Each element initially gets a "zero-equivalent" value. Type int 0 Default value double 0.0 boolean String or other object false null (means, "no object") 6

7 Accessing elements name[index] name[index] = value; // access // modify Example: numbers[0] = 27; numbers[3] = -6; System.out.println(numbers[0]); if (numbers[3] < 0) { System.out.println("Element 3 is negative."); index value

8 Arrays of other types double[] results = new double[5]; results[2] = 3.4; results[4] = -0.5; index value boolean[] tests = new boolean[6]; tests[3] = true; index value false false false true false false 10

9 Out-of-bounds Legal indexes: between 0 and the array's length - 1. Reading or writing any index outside this range will throw an ArrayIndexOutOfBoundsException. Example: int[] data = new int[10]; System.out.println(data[0]); System.out.println(data[9]); System.out.println(data[-1]); System.out.println(data[10]); // okay // okay // exception // exception index value

10 Ways of Accessing Arrays Sequential Access: accessing and/or manipulating elements of array in a sequential manner from first element to last element for loops Random Access: accessing and/or manipulating elements of array in any order whatsoever with quick access to each element element by index 10

11 Accessing array elements randomly example int[] numbers = new int[8]; numbers[1] = 3; numbers[4] = 99; numbers[6] = 2; int x = numbers[1]; numbers[x] = 42; numbers[numbers[6]] = 11; // use numbers[6] as index x index numbers value 11

12 Accessing array elements randomly example solution int[] numbers = new int[8]; numbers[1] = 3; numbers[4] = 99; numbers[6] = 2; int x = numbers[1]; numbers[x] = 42; numbers[numbers[6]] = 11; // use numbers[6] as index x 3 numbers index value

13 Accessing array elements randomly another problem int[] data = new int[8]; data[7] = 3; data[4] = 1; int x = data[2]; data[2] = 31; data[x] = 4; data[data[0]] = 6; x index data value 13

14 Arrays and for loops (Sequential Access) It is common to use for loops to access array elements. for (int i = 0; i < 8; i++) { System.out.print(numbers[i] + " "); System.out.println(); // output: Sometimes we assign each element a value in a loop. for (int i = 0; i < 8; i++) { numbers[i] = 2 * i; index value

15 The length field An array's length field stores its number of elements. name.length for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); // output: It does not use parentheses like a String's.length(). What expressions refer to: The last element of any array? The middle element? The first element? 15

16 The length field (cont) Last element: numbers[numbers.length 1]; Middle element: numbers[numbers.length / 2]; Middle element: numbers[(numbers.length - 1) / 2]; First element: numbers[0]; 16

17 Initializing Arrays User Input Because arrays are indexed, using a loop to initialize arrays is really efficient Prompt the user for the size of the array and then create an integer array of that size and fill with values that are prompted from the user. Scanner console = new Scanner(System.in); System.out.print("How many numbers? "); int size = console.nextint(); int[] array = new int[size]; for (int i = 0; i < array.length; i++) { System.out.print("Integer: "); while(!console.hasnextint()){ console.next(); System.out.println("Not an integer"); System.out.print("Integer: "); array[i] = console.nextint(); 17

18 Initializing Arrays Random Create and fill a 100 element integer array with random values between 0 and 99, inclusive. public static final int ARRAY_SIZE = 100; public static final int VALUE_RANGE = 100; Random r = new Random(); int[] a = new int[array_size]; for (int i = 0; i < a.length; i++) { a[i] = r.nextint(value_range); 20

19 Quick array initialization You can also create an array and give it initial values for each element using a shortcut: type[] name = {value, value, value; Example: int[] numbers = {12, 49, -2, 26, 5, 17, -6; index value Useful when you know what the array's elements will be The compiler figures out the size by counting the values 19

20 "Array mystery" problem What element values are stored in the following array? int[] a = {1, 7, 5, 6, 4, 14, 11; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; index value 20

21 "Array mystery" solution What element values are stored in the following array? int[] a = {1, 7, 5, 6, 4, 14, 11; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; index value

22 Array traversals traversal: An examination of each element of an array. for (int i = 0; i < array.length; i++) { do something with array[i]; Examples: printing the elements searching for a specific value rearranging the elements computing the sum, product, etc. 22

23 Back to the Weather question Use an array to solve the weather problem: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = days were above average. 23

24 Weather answer // Reads temperatures from the user, computes average and # days import java.util.*; above average. public class Weather { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("How many days' temperatures? "); int days = console.nextint(); int[] temps = new int[days]; int sum = 0; // array to store days' temperatures for (int i = 0; i < days; i++) { System.out.print("Day " + (i + 1) + "'s high temp: temps[i] = console.nextint(); sum += temps[i]; double average = (double) sum / days; // read/store each day's temperature "); int count = 0; for (int i = 0; i < days; i++) { if (temps[i] > average) { count++; // see if each day is above average // report results System.out.printf("Average System.out.println(count + temp = " days %.1f\n", average); above average"); 26

25 Lab Exercise Go to the moodle page and work on the ArrayCalculations.java assignment: Write a class called ArrayCalculations that does the following: Declares an integer array named data with the elements 7, -1, 13, 24, and 6. Use only one statement to initialize the array. Calculates and prints the maximum value in the array. Calculates and prints the minimum value in the array. Calculates and prints the sum of all the elements in the array. Calculates and prints the average (a double) of all the elements in the array. System.out.println("\nThe maximum value in the array is: " + maximum); System.out.println("The minimum value in the array is: " + minimum); System.out.println("The sum of the values in the array is: " + sum); System.out.println("The average of the values in the array is: " + average); 27

Building Java Programs

Building Java Programs Building Java Programs Chapter 7 Arrays reading: 7.1 2 Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp:

More information

Topic 21 arrays - part 1

Topic 21 arrays - part 1 Topic 21 arrays - part 1 "Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration. " - Stan Kelly-Bootle Copyright Pearson Education, 2010 Based

More information

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D. Topic 21 https://commons.wikimedia.org/w/index.php?curid=66702 arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether,

More information

AP Computer Science. Arrays. Copyright 2010 by Pearson Education

AP Computer Science. Arrays. Copyright 2010 by Pearson Education AP Computer Science Arrays Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com

More information

Building Java Programs Chapter 7

Building Java Programs Chapter 7 Building Java Programs Chapter 7 Arrays Copyright (c) Pearson 2013. All rights reserved. Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day

More information

Array basics. Readings: 7.1

Array basics. Readings: 7.1 Array basics Readings: 7.1 1 How would you solve this? Consider the following program: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp:

More information

Lecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved.

Lecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved. Lecture 9: Arrays Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Can we solve this problem? Consider the following program

More information

Array basics. How would you solve this? Arrays. What makes the problem hard? Array auto-initialization. Array declaration. Readings: 7.

Array basics. How would you solve this? Arrays. What makes the problem hard? Array auto-initialization. Array declaration. Readings: 7. How would you solve this? Array basics Readings:. Consider the following program: How many days' temperatures? Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp:

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com

More information

CSE 143 Lecture 1. Arrays (review) slides created by Marty Stepp

CSE 143 Lecture 1. Arrays (review) slides created by Marty Stepp CSE 143 Lecture 1 Arrays (review) slides created by Marty Stepp http://www.cs.washington.edu/143/ Arrays (7.1) array: An object that stores many values of the same type. element: One value in an array.

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin. q Puzzle Day

More information

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements Admin. CS 112 Introduction to Programming q Puzzle Day from Friday to Monday Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email:

More information

CSc 110, Autumn 2016 Lecture 15: lists. Adapted from slides by Marty Stepp and Stuart Reges

CSc 110, Autumn 2016 Lecture 15: lists. Adapted from slides by Marty Stepp and Stuart Reges CSc 110, Autumn 2016 Lecture 15: lists Adapted from slides by Marty Stepp and Stuart Reges Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day

More information

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]

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

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

More information

Last Class. More on loops break continue A bit on arrays

Last Class. More on loops break continue A bit on arrays Last Class More on loops break continue A bit on arrays public class February2{ public static void main(string[] args) { String[] allsubjects = { ReviewArray, Example + arrays, obo errors, 2darrays };

More information

CS 106A, Lecture 16 Arrays

CS 106A, Lecture 16 Arrays CS 106A, Lecture 16 Arrays suggested reading: Java Ch. 11.1-11.5 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

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

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

Arrays in Java Using Arrays

Arrays in Java Using Arrays Recall Length of an Array Arrays in Java Using Arrays Once an array has been created in memory, its size is fixed for the duration of its existence. Every array object has a length field whose value can

More information

Arrays. Eng. Mohammed Abdualal

Arrays. Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays

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

Arrays Chris Piech CS106A, Stanford University

Arrays Chris Piech CS106A, Stanford University Arrays Chris Piech CS106A, Stanford University What does this say? 53 305))6*;4826)4 )4 );806*;48 8 60))85;1 (;: *8 83(88)5* ;46(;88*96*?;8)* (;485);5* 2:* (;4956*2(5* 4)8 8*;4069285);)6 8)4 ;1( 9;48081;8:8

More information

Computer programming Code exercises [1D Array]

Computer programming Code exercises [1D Array] Computer programming-140111014 Code exercises [1D Array] Ex#1: //Program to read five numbers, from user. public class ArrayInput public static void main(string[] args) Scanner input = new Scanner(System.in);

More information

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright

More information

Topic 12 more if/else, cumulative algorithms, printf

Topic 12 more if/else, cumulative algorithms, printf Topic 12 more if/else, cumulative algorithms, printf "We flew down weekly to meet with IBM, but they thought the way to measure software was the amount of code we wrote, when really the better the software,

More information

Example: Computing prime numbers

Example: Computing prime numbers Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will

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

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises: #7 videos: Ch. 4 #2-4 The if/else statement Executes one block if a test is true,

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays WIT COMP1000 Arrays Arrays An array is a list of variables of the same type, that represents a set of related values For example, say you need to keep track of the cost of 1000 items You could declare

More information

Lab Assignment Three

Lab Assignment Three Lab Assignment Three C212/A592 Fall Semester 2010 Due in OnCourse by Friday, September 17, 11:55pm (Dropbox will stay open until Saturday, September 18, 11:55pm) Abstract Read and solve the problems below.

More information

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz The in-class quiz is intended to give you a taste of the midterm, give you some early feedback about

More information

Chapter 7: Arrays and the ArrayList Class

Chapter 7: Arrays and the ArrayList Class Chapter 7: Arrays and the ArrayList Class Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 7 discusses the following main topics: Introduction

More information

Midterm Examination (MTA)

Midterm Examination (MTA) M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1 self-check: Ch. 4 #2; Ch. 5 # 1-10 exercises: Ch. 4 #2, 4, 5, 8; Ch. 5 # 1-2 Copyright 2009

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

Searching and Sorting (Savitch, Chapter 7.4)

Searching and Sorting (Savitch, Chapter 7.4) Searching and Sorting (Savitch, Chapter 7.4) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort What is an algorithm? A finite set of precise instruc6ons for performing

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

What is an algorithm?

What is an algorithm? /0/ What is an algorithm? Searching and Sorting (Savitch, Chapter 7.) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort A finite set of precise instrucons for performing

More information

Computação I. Exercises. Leonardo Vanneschi NOVA IMS, Universidade Nova de Lisboa. Leonardo Vanneschi Computação I NOVA IMS

Computação I. Exercises. Leonardo Vanneschi NOVA IMS, Universidade Nova de Lisboa. Leonardo Vanneschi Computação I NOVA IMS Computação I Exercises Leonardo Vanneschi NOVA IMS, Universidade Nova de Lisboa 1 Exercise 1 Write a Java program composed by: a. A method called myaverage that has the following parameters: an array A

More information

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4: Conditional Execution 1 loop techniques cumulative sum fencepost loops conditional execution Chapter outline the if statement and the if/else statement relational expressions

More information

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education AP Computer Science Return values, Math, and double Distance between points Write a method that given x and y coordinates for two points prints the distance between them If you can t do all of it, pseudocode?

More information

assertion: A statement that is either true or false.

assertion: A statement that is either true or false. Logical assertions assertion: A statement that is either true or false. Examples: Java was created in 1995. The sky is purple. 23 is a prime number. 10 is greater than 20. x divided by 2 equals 7. (depends

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else; Cumulative sum; reading: 4.2, 4.4-4.5 2 Advanced if/else reading: 4.4-4.5 Factoring if/else code factoring: Extracting common/redundant code.

More information

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Lecture 10: Arrays II

Lecture 10: Arrays II Lecture 10: Arrays II Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Largest Value Given an array, return the largest

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

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

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review

More information

Lecture 17. For Array Class Shenanigans

Lecture 17. For Array Class Shenanigans Lecture 17 For Array Class Shenanigans For or While? class WhileDemo { public static void main(string[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; Note:

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner 1 Lecture outline console input with Scanner objects input tokens Scanner as a parameter to a method cumulative

More information

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution https://www.dignitymemorial.com/obituaries/brookline-ma/adele-koss-5237804 Topic 11 Scanner object, conditional execution Logical thinking and experience was as important as theory in using the computer

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com

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

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

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam Seat Number Name CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam This is a closed book exam. Answer all of the questions on the question paper in the space provided. If

More information

1. An operation in which an overall value is computed incrementally, often using a loop.

1. An operation in which an overall value is computed incrementally, often using a loop. Practice Exam 2 Part I: Vocabulary (10 points) Write the terms defined by the statements below. 1. An operation in which an overall value is computed incrementally, often using a loop. 2. The < (less than)

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1, 4.5 2 Interactive Programs with Scanner reading: 3.3-3.4 Interactive programs We have written programs that print console

More information

Chapter 2: Basic Elements of Java

Chapter 2: Basic Elements of Java Chapter 2: Basic Elements of Java TRUE/FALSE 1. The pair of characters // is used for single line comments. ANS: T PTS: 1 REF: 29 2. The == characters are a special symbol in Java. ANS: T PTS: 1 REF: 30

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

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

Advanced if/else & Cumulative Sum

Advanced if/else & Cumulative Sum Advanced if/else & Cumulative Sum Subset of the Supplement Lesson slides from: Building Java Programs, Chapter 4 by Stuart Reges and Marty Stepp (http://www.buildingjavaprograms.com/ ) Questions to consider

More information

1. What does the following code fragment write to the monitor?

1. What does the following code fragment write to the monitor? 1. What does the following code fragment write to the monitor? int sum = 14; if ( sum < 20 ) System.out.print("Under "); else System.out.print("Over "); System.out.println("the limit."); a. Under b. Over

More information

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes Motivation of Loops Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG We may want to repeat the similar action(s) for a (bounded) number of times. e.g., Print the Hello World message

More information

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for and while Primitive

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises: #7 videos: Ch. 4 #2-4 Loops with if/else if/else statements can be used with

More information

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays Lecture 17 Instructor: Craig Duckett Passing & Returning Arrays Assignment Dates (By Due Date) Assignment 1 (LECTURE 5) GRADED! Section 1: Monday, January 22 nd Assignment 2 (LECTURE 8) GRADED! Section

More information

CIS November 14, 2017

CIS November 14, 2017 CIS 1068 November 14, 2017 Administrative Stuff Netflix Challenge New assignment posted soon Lab grades Last Time. Building Our Own Classes Why Abstraction More on the new operator Fields Class vs the

More information

CIS 1068 Netflix Challenge New assignment posted soon Lab grades November 14, 2017

CIS 1068 Netflix Challenge New assignment posted soon Lab grades November 14, 2017 Administrative Stuff CIS 1068 Netflix Challenge New assignment posted soon Lab grades November 14, 2017 Last Time. Building Our Own Classes Why Abstraction More on the new operator Fields Class vs the

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin

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

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

Passing Array to Methods

Passing Array to Methods Passing Array to Methods Lecture 13 Based on Slides of Dr. Norazah Yusof 1 Passing Array Elements to a Method When a single element of an array is passed to a method it is handled like any other variable.

More information

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays:

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays: College of Computer and Information Sciences CSC111 Computer Programming I Exercise 1: Tutorial 11 Arrays: A. Write a code snippet to define the following arrays: 1. An int array named nums of size 10.

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

Arrays Chris Piech CS106A, Stanford University

Arrays Chris Piech CS106A, Stanford University Arrays Chris Piech CS106A, Stanford University Changing Variable Types int to double? int x = 5; double xdbl = x; int to String? int x = 5; String xstr = + x String to int? String xstr = 5 ; int x = Integer.parseInt(x);

More information

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp! Garfield AP CS User Input, If/Else Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp! Warmup Write a method add10 that takes one integer parameter. Your method should return

More information

Full file at

Full file at Chapter 1 1. a. False; b. False; c. True; d. False; e. False; f; True; g. True; h. False; i. False; j. True; k. False; l. True. 2. Keyboard and mouse. 3. Monitor and printer. 4. Because programs and data

More information

Topic 12 more if/else, cumulative algorithms, printf

Topic 12 more if/else, cumulative algorithms, printf Topic 12 more if/else, cumulative algorithms, printf "We flew down weekly to meet with IBM, but they thought the way to measure software was the amount of code we wrote, when really the better the software,

More information

Spring 2010 Java Programming

Spring 2010 Java Programming Java Programming: Guided Learning with Early Objects Chapter 7 - Objectives Learn about arrays Explore how to declare and manipulate data in arrays Learn about the instance variable length Understand 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

Data dependent execution order data dependent control flow

Data dependent execution order data dependent control flow Chapter 5 Data dependent execution order data dependent control flow The method of an object processes data using statements, e.g., for assignment of values to variables and for in- and output. The execution

More information

Chapter 2. Elementary Programming

Chapter 2. Elementary Programming Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s);

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignment Class Exercise 19 is assigned Homework 8 is assigned Both Homework 8 and Exercise 19 are

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

Topic 22 arrays - part 2. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

Topic 22 arrays - part 2. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/ Swapping values public static void main(string[] args)

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

AP Programming - Chapter 6 Lecture

AP Programming - Chapter 6 Lecture page 1 of 21 The while Statement, Types of Loops, Looping Subtasks, Nested Loops I. The while Statement Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly.

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

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) 1 Short Answer (10 Points Each) 1. For the following one-dimensional array, show the final array state after each pass of the three sorting algorithms. That is, after each iteration of the outside loop

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