Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

Size: px
Start display at page:

Download "Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey"

Transcription

1 Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

2 Current Options for Storing Data 1) You need to store the room temperature, such as 62.5, in a variable. What would you use? a variable of type double, such as double roomtempf = 62.5; 2) You need to store all the attributes for an automobile (such as color, mileage, engine type, cost) in a variable. What would you use? an object of class Car, such as: Car auto = new Car(Color.red,42,"hybrid", 20000); you would have to define the Car class yourself 1-2

3 A new need, storing many of one type 3) You need to store the high temperature every day for the last year, what would you use? an array of double, such as double [] dailyhigh = new double[365]; 4) You need to store the inventory of all 1200 cars you're trying to sell, what would you use? an array of class Car, such as: Car [] inventory = new Car[1200]; 1-3

4 Review: Two Ways of Representing Information in Java Primitive types a single quantity int x = 6; x 6 Object types a single entity with multiple attributes Point center= new Point(1,8); 1-4

5 Arrays: a third way of representing information An array is a set of values where each value is identified by an index. array elements int size = 6; array index 1-5

6 Access Array Elements using the [ ] operator Note: as with String, elements go from 0 to 3 count[4] = 2; ArrayOutOfBounds Execption What does this do? count[ count[2] ] = 5; 1-6

7 Using a Loop (Traversal) to print all the items Standard while loop i goes from 0 to 3 When i gets to 4, loop condition fails, exit count[4] is not accessed 1-7

8 For Loops Has same components as while loop More compact, all control info in header The general syntax looks like this: Equivalent to this while loop: 1-8

9 Example: For vs While Loop This for loop Works the same as this while loop 1-9

10 Array Length All arrays have one named instance variable: length Holds the size of the array how many items it can store better to use length field as upper bound of loop last time body of loop is executed is when i = count.length 1 (position of last element) 1-10

11 Array Initialization When relatively few items need to be initialized, an initialization list can be used to initialize the array. int[] highs = {65, 69, 72, 78, 61 }; The numbers in the list are stored in the array in order: highs[0] is assigned 65, highs[1] is assigned 69, highs[2] is assigned 72, highs[3] is assigned 78, highs[4] is assigned

12 Review: The Scanner Class To read input from the keyboard we can use the Scanner class. The Scanner class is defined in java.util, so we will use the following statement at the top of our programs: import java.util.scanner; To create a Scanner object: Scanner keyboard = new Scanner(System.in); 2-12

13 Read from keyboard with Scanner Examples read the next word (til next white space) as String String word = keyboard.next(); read to the end of the line as a String String line = keyboard.nextline(); read the next number as an int int x = keyboard.nextint(); read the next number as a double double y = keyboard.nextdouble(); 2-13

14 Do Lab 12 Part A (Problems 1 through 5) 1-14

15 Checkpoint

16 Checkpoint int [] employeenumbers = new int[100]; double [] payrates = new double[25]; 0 to

17 Checkpoint

18 Checkpoint result = numbers1[0]*numbers2[3]; for (int k=0; k<array.length; k++) array[k]=-1;

19 Copying Arrays wrong way x Creates one array of three doubles Copies reference to array from variable a to b Doesn't make a separate copy A form of aliasing Change in one array show up in the other 1-19

20 Side effects of Aliasing a[1] = 8.1; System.out.println( b[1] ) // prints 8.1 b[2] = 3.4; System.out.println( a[2] ) // prints

21 Copying Arrays Right Way 1-21

22 Using a For Loop to do the same For loop that uses the length of a as the size: 1-22

23 Arrays and Objects In many ways, arrays behave like objects: When you declare an array variable, you get a reference to an array. You have to use new to create the array itself. When you pass an array as an argument, you pass a reference, which means that the invoked method can change the contents of the array. 1-23

24 Difference between a Rectangle A Rectangle object and an Array of 4 int? Change first value in Rectangle box.x = 25; // fields referred to by name 1-24

25 Difference between a Rectangle and an Array of 4 int? An Array of 4 int elements: int [] box = {0,0,100,100}; Change first value in box array: box[0] = 25; // elements referred to by index 1-25

26 Another difference: Array elements must all have same type Objects of class Tile have a char and an int class Tile { } char letter; int value; An array can only hold all char data or all int data, not both, so this could not be represented using an array. 1-26

27 Do Lab 12 Part B (Problems 6-8) 1-27

28 Random Numbers Most computer programs are deterministic do the same thing each time they run usually a good thing same calculation should give the same result Some applications need to be unpredictable Games, modeling complicated systems (weather) Sources of truly random numbers:

29 Assignment 12 The following slides are to help you visualize the goal of the code you are writing in assignment

30 Pseudorandom Numbers We can make computers seem nondeterministic generate numbers using a math formula built into Math.random method code to print 10 pseudorandom numbers: 1-30

31 Math.random method 1-31

32 Arithmetic with Random Numbers What if you print x *10? 10 + x? (int) (x*6) + 1; 1-32

33 Assignment 12 problem 2 Write a method randomint(int low, int high) returns a random number between low (inclusive) and high (exclusive). Math notation: [low, high) randomint(15, 20) produces randomly 1-33

34 Method to create a random array // in main: int [] arr = randomarray(8); 1-34

35 Method to print an array // in main: int [] arr = randomarray(8); printarray( arr ); 1-35

36 Counting Suppose the array arr contains test scores: How many A's were there? How many B's? int counta = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= 90) counta++; } 1-36

37 A method that counts how many values an array has in a given range // in main int numas = inrange( arr, 90, 101); int numbs = inrange( arr, 80, 90); notice, no {} needed when only 1 statement in if statement true block 1-37

38 Number of Tests Histogram of Test 2 Scores int [ ] scores = {98, 86, 79, 90, 89, 88, 88, 97, 92, 90, 87, 69, 66, 60, 86, 85, 84, 77, 53, 90, 79, 90, 87, 74}; Test Score process scores array into a second array that holds the counts for each possible test score 1-38

39 One way to create a Histogram Make a separate variable for each count? int count0 = inrange(scores, 0, 1); int count1 = inrange(scores, 1, 2); int count2 = inrange(scores, 2, 3);... int count99 = inrange(scores, 99, 100); painful! How about an array to hold all the counts? 1-39

40 Better way to create a Histogram Make an array to hold all the counts! int[] counts = new int[100]; for (int i = 0; i < counts.length; i++){ counts[i] = inrange(scores, i, i+1); } Note variable i being used to index counts AND provide limits to inrange How many times do we have to traverse the scores array? 1-40

41 More efficiently create a Histogram Use the test score itelf as the index to counts! int[] counts = new int[100]; for (int i = 0; i < scores.length; i++){ int index = scores[i]; counts[index]++; } only makes one pass through scores array runs much faster: O(n) vs O(n 2 ) 1-41

42 Draw a Histogram bar chart int [] arr = { 4,2,4,2,1,2,0,3,0,0,1,2,2}; int [] counts; < make a histogram of arr > [0] XXX [1] XX [2] XXXXX [3] X [4] XX After you've processed data from arr into counts Make a for loop that repeats the number of elements in counts array print the index, then on same line, call bar on counts[index] to print row of X's 1-42

43 A method that prints a horizontal bar bar(5); // bar(8); // prints XXXXX prints XXXXXXXX pseudocode: method bar, takes parameter length loop that repeats length times print 1 "X" to console after loop, go to new line (println) 1-43

44 Sorting Arrays [Optional] Computer scientists often need to sort arrays Why? Because it s easier to find things in the array when it is sorted Most data looks better displayed in sorted form (phone books, employee records, Lacrosse games) How can we sort an array? What is the algorithm? A: There are several!! 44

45 Bubble Sort Bubble sort is one of the simplest sorting algorithms It proceeds through a sequence of iterations, each time moving the next largest item into its correct position On each iteration, it compares each pair of consecutive elements, moving the larger element up 45

46 Bubble Sort data

47 Bubble Sort data if (data[k] > data[k+1]) > 55? 47

48 Bubble Sort data swap(data, k, k+1); swap 48

49 Bubble Sort data

50 Bubble Sort data > 55? 50

51 Bubble Sort data

52 Bubble Sort data > 99? 52

53 Bubble Sort data swap 53

54 Bubble Sort data Notice how the data bubbles up through the array moving slowly, one bin at a time After N-1 Passes or Sweeps, the final array is guaranteed to be sorted in ascending order, no matter what input data 54

55 Selection Sort Another way of sorting is the selection sort The main idea is to keep finding the smallest (and next smallest) items in the array And move them into correct position (swap) 55

56 Selection Sort data smallest 55 small_pos 0 k 0 55 < smallest? F 56

57 Selection Sort data smallest 55 small_pos 0 k 0 22 < smallest? T 57

58 Selection Sort data smallest 22 small_pos 1 k 0 22 < smallest? T 58

59 Selection Sort data smallest 22 small_pos 1 k 0 99 < smallest? F 59

60 Selection Sort data smallest 22 small_pos 1 k 0 66 < smallest? F 60

61 Selection Sort SWAP data smallest 22 small_pos 1 k 0 swap(data, k, small_pos); 61

62 Selection Sort Repeat smallest 55 small_pos 1 k 1 55 < smallest? F 62

63 Swapping two array elements public static void swap( int [] arr, int j, int k) { int temp = arr[j]; arr[j] = arr[k]; arr[k] = temp; } 1-63

Chapter 4: Conditionals and Recursion

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

More information

LAB 7. Objectives: Navin Sridhar D 8 54

LAB 7. Objectives: Navin Sridhar D 8 54 LAB 7 Objectives: 1. Learn to create and define constructors. 2. Understand the use and application of constructors & instance variables. 3. Experiment with the various properties of arrays. 4. Learn to

More information

LAB 13: ARRAYS (ONE DIMINSION)

LAB 13: ARRAYS (ONE DIMINSION) Statement Purpose: The purpose of this Lab. is to practically familiarize student with the concept of array and related operations performed on array. Activity Outcomes: As a second Lab on Chapter 7, this

More information

1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) Name: Write all of your responses on these exam pages. 1 Short Answer (10 Points Each) 1. What is the difference between a compiler and an interpreter? Also, discuss how Java accomplishes this task. 2.

More information

Chapter 13: Arrays of Objects

Chapter 13: Arrays of Objects Chapter 13: Arrays of Objects Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey As in Chapter 11, we will be following a more standard approach than the one taken by Downey in

More information

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof Array Lecture 12 Based on Slides of Dr. Norazah Yusof 1 Introducing Arrays Array is a data structure that represents a collection of the same types of data. In Java, array is an object that can store a

More information

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

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

Chapter 6 Arrays. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 6 Arrays 1 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. 2 Solution AnalyzeNumbers Run Run with prepared input 3 Objectives

More information

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

Assignment 2.4: Loops

Assignment 2.4: Loops Writing Programs that Use the Terminal 0. Writing to the Terminal Assignment 2.4: Loops In this project, we will be sending our answers to the terminal for the user to see. To write numbers and text to

More information

Chapter 11: Create Your Own Objects

Chapter 11: Create Your Own Objects Chapter 11: Create Your Own Objects Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Our usual text takes a fairly non-standard departure in this chapter. Instead, please refer

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

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

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

Chapter 5 Lab Methods

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

More information

4. Java language basics: Function. Minhaeng Lee

4. Java language basics: Function. Minhaeng Lee 4. Java language basics: Function Minhaeng Lee Review : loop Program print from 20 to 10 (reverse order) While/for Program print from 1, 3, 5, 7.. 21 (two interval) Make a condition that make true only

More information

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.

More information

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages Topic 1: Basic Java Plan: this topic through next Friday (5 lectures) Required reading on web site I will not spell out all the details in lecture! BlueJ Demo BlueJ = Java IDE (Interactive Development

More information

Chapter 5 Lab Methods

Chapter 5 Lab Methods Gaddis_516907_Java 4/10/07 2:10 PM Page 41 Chapter 5 Lab Methods Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation for our

More information

Chapter 8 Multi-Dimensional Arrays

Chapter 8 Multi-Dimensional Arrays Chapter 8 Multi-Dimensional Arrays 1 1-Dimentional and 2-Dimentional Arrays In the previous chapter we used 1-dimensional arrays to model linear collections of elements. myarray: 6 4 1 9 7 3 2 8 Now think

More information

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS 152: Data Structures with Java Hello World with the IntelliJ IDE CS 152: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Electrical and Computer Engineering building

More information

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 6 Single-Dimensional Arrays rights reserved. 1 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. Solution AnalyzeNumbers rights

More information

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE Looking for something COMP 10 EXPLORING COMPUTER SCIENCE Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE Searching algorithms Linear search Complexity Sorting algorithms

More information

Arrays and Strings. Arash Rafiey. September 12, 2017

Arrays and Strings. Arash Rafiey. September 12, 2017 September 12, 2017 Arrays Array is a collection of variables with the same data type. Arrays Array is a collection of variables with the same data type. Instead of declaring individual variables, such

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Basic Computation Chapter 2 Increment and Decrement Operators Used to increase (or decrease) the value of a variable by 1 Easy to use, important to recognize The increment operator count++ or ++count The

More information

Intro to Programming in Java Practice Midterm

Intro to Programming in Java Practice Midterm 600.107 Intro to Programming in Java Practice Midterm This test is closed book/notes. SHORT ANSWER SECTION [18 points total] 1) TRUE/FALSE - Please circle your choice: Tr for true, Fa for false. [1 point

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

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

CSE 1223: Exam II Autumn 2016

CSE 1223: Exam II Autumn 2016 CSE 1223: Exam II Autumn 2016 Name: Instructions: Do not open the exam before you are told to begin. This exam is closed book, closed notes. You may not use any calculators or any other kind of computing

More information

A+ Computer Science -

A+ Computer Science - import java.util.scanner; or just import java.util.*; reference variable Scanner keyboard = new Scanner(System.in); object instantiation Scanner frequently used methods Name nextint() nextdouble() nextfloat()

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

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points. Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points. Use the remaining question as extra credit (worth 1/2 of the points earned). Specify which question is

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Chapter 5 Lab Methods

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

More information

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

BASIC INPUT/OUTPUT. Fundamentals of Computer Science BASIC INPUT/OUTPUT Fundamentals of Computer Science Outline: Basic Input/Output Screen Output Keyboard Input Simple Screen Output System.out.println("The count is " + count); Outputs the sting literal

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

Robots. Byron Weber Becker. chapter 6

Robots. Byron Weber Becker. chapter 6 Using Variables Robots Learning to Program with Java Byron Weber Becker chapter 6 Announcements (Oct 5) Chapter 6 You don t have to spend much time on graphics in Ch6 Just grasp the concept Reminder: Reading

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

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS BİLGE KÖROĞLU Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS Method Decomposition: Every method should be understandable therefore sometimes wee need to decompose some methods into smaller

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

More information

Chapter 7: Arrays CS 121. April 9, Department of Computer Science College of Engineering Boise State University. Chapter 7: Arrays CS / 41

Chapter 7: Arrays CS 121. April 9, Department of Computer Science College of Engineering Boise State University. Chapter 7: Arrays CS / 41 Chapter 7: Arrays CS 121 Department of Computer Science College of Engineering Boise State University April 9, 2015 Chapter 7: Arrays CS 121 1 / 41 Topics Array declaration and use Bounds checking Arrays

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

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks?

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks? Types in Java 8 Primitive Types byte, short, int, long float, double boolean Char Object types: predefined e.g. String ; User-defined via class and constructors What if we want to store lots of items e.g.

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

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

Over and Over Again GEEN163

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

More information

Programming with Java

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

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

CS1150 Principles of Computer Science Arrays

CS1150 Principles of Computer Science Arrays CS1150 Principles of Computer Science Arrays Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Read one hundred numbers, compute their

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

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

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

COMP String and Console I/O. Yi Hong May 18, 2015

COMP String and Console I/O. Yi Hong May 18, 2015 COMP 110-001 String and Console I/O Yi Hong May 18, 2015 Announcements Labs 0 & 1 are due today by 11:59pm Homework 0 grades are posted Office hours are fixed: MW 3-4pm, or by appointment Review of How

More information

Subject: Computer Science

Subject: Computer Science Subject: Computer Science Topic: Data Types, Variables & Operators 1 Write a program to print HELLO WORLD on screen. 2 Write a program to display output using a single cout statement. 3 Write a program

More information

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

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

More information

STUDENT LESSON A12 Iterations

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

More information

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

COMP Computer Basics. Yi Hong May 13, 2015

COMP Computer Basics. Yi Hong May 13, 2015 COMP 110-001 Computer Basics Yi Hong May 13, 2015 Today Hardware and memory Programs and compiling Your first program 2 Before Programming Need to know basics of a computer Understand what your program

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

LECTURE 17. Array Searching and Sorting

LECTURE 17. Array Searching and Sorting LECTURE 17 Array Searching and Sorting ARRAY SEARCHING AND SORTING Today we ll be covering some of the more common ways for searching through an array to find an item, as well as some common ways to sort

More information

2. What are the two main components to the CPU and what do each of them do? 3. What is the difference between a compiler and an interpreter?

2. What are the two main components to the CPU and what do each of them do? 3. What is the difference between a compiler and an interpreter? COSC 117 Final Exam Spring 2011 Name: Part 1: Definitions & Short Answer (3 Points Each) 1. What do CPU and ALU stand for? 2. What are the two main components to the CPU and what do each of them do? 3.

More information

Chapter 7 Single-Dimensional Arrays

Chapter 7 Single-Dimensional Arrays Chapter 7 Single-Dimensional Arrays 1 Arrays Array is a data structure that represents a collection of same-types data elements. A single-dimensional array is one that stores data elements in one row.

More information

ITI1120 Introduction to Computing I Exercise Workbook Fall 2012

ITI1120 Introduction to Computing I Exercise Workbook Fall 2012 ITI1120 Introduction to Computing I Exercise Workbook Fall 2012 1 Table of Contents 1 Introduction 3 2 Computer Programming Model 3 3 Pre-defined Algorithm Models 6 4 Summary of Program Structure, Algorithm

More information

Java Programming. Computer Science 112

Java Programming. Computer Science 112 Java Programming Computer Science 112 Review: Problem solving Class 4 is the Whole Point of Programming. Is there any particular one you'd like to go through? If you are desperately confused still, now

More information

Ch. 6. User-Defined Methods

Ch. 6. User-Defined Methods Ch. 6 User-Defined Methods Func5onal Abstrac5on Func5onal regarding func5ons/methods Abstrac5on solving a problem in a crea5ve way Stepwise refinement breaking down large problems into small problems The

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

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal APCS A Midterm Review You will have a copy of the one page Java Quick Reference sheet. This is the same reference that will be available to you when you take the AP Computer Science exam. 1. n bits can

More information

Flow of Control. Chapter 3

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

More information

8.14 Exercises 101. // if n is even, the result is t squared // if n is odd, the result is t squared times x

8.14 Exercises 101. // if n is even, the result is t squared // if n is odd, the result is t squared times x 8.14 Exercises 101 Type in this code and try out a few simple cases like creating a BigInteger and printing it. Notice that println knows how to print BigIntegers! Don t forget to add import java.math.biginteger

More information

5/31/2006. Last Time. Announcements. Today. Variable Scope. Variable Lifetime. Variable Scope - Cont. The File class. Assn 3 due this evening.

5/31/2006. Last Time. Announcements. Today. Variable Scope. Variable Lifetime. Variable Scope - Cont. The File class. Assn 3 due this evening. Last Time Announcements The File class. Back to methods Passing parameters by value and by reference. Review class attributes. An exercise to review File I/O, look at passing by reference and the use of

More information

Input. Scanner keyboard = new Scanner(System.in); String name;

Input. Scanner keyboard = new Scanner(System.in); String name; Reading Resource Input Read chapter 4 (Variables and Constants) in the textbook A Guide to Programming in Java, pages 77 to 82. Key Concepts A stream is a data channel to or from the operating system.

More information

Chapter 1 Lab Algorithms, Errors, and Testing

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

More information

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

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

More information

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by Addison-Wesley

More information

Functions. Arash Rafiey. September 26, 2017

Functions. Arash Rafiey. September 26, 2017 September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff(); COSC 117 Exam 3 Key Fall 2012 Part 1: Definitions & Short Answer (3 Points Each) 1. A method in a class that has no return type and the same name as the class is called what? How is this type of method

More information

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 6: Arrays Arrays An array is an ordered list of values Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking The

More information

Pace University. Fundamental Concepts of CS121 1

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

More information

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

Lecture #8-10 Arrays

Lecture #8-10 Arrays Lecture #8-10 Arrays 1. Array data structure designed to store a fixed-size sequential collection of elements of the same type collection of variables of the same type 2. Array Declarations Creates a Storage

More information

Chapter 4 Lab. Loops and Files. Objectives. Introduction

Chapter 4 Lab. Loops and Files. Objectives. Introduction Chapter 4 Lab Loops and Files Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write a do-while loop Be able to write a for loop Be

More information

&KDSWHU$UUD\VDQG9HFWRUV

&KDSWHU$UUD\VDQG9HFWRUV &KDSWHU$UUD\VDQG9HFWRUV Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus Java Software Solutions is published by Addison-Wesley

More information

Formatting Output & Enumerated Types & Wrapper Classes

Formatting Output & Enumerated Types & Wrapper Classes Formatting Output & Enumerated Types & Wrapper Classes Quick review of last lecture September 8, 2006 ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev

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

Flow of Control. Chapter 3

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

More information

Arrays. CS Feb 2008

Arrays. CS Feb 2008 Arrays CS 180 15 Feb 2008 Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb Snakes & Ladders Game Review of Q5,Q8,Q11 & Programming Questions Arrays:

More information

A+ Computer Science -

A+ Computer Science - Visit us at www.apluscompsci.com Full Curriculum Solutions M/C Review Question Banks Live Programming Problems Tons of great content! www.facebook.com/apluscomputerscience import java.util.scanner; Try

More information

Introduction. two of the most fundamental concepts in computer science are, given an array of values:

Introduction. two of the most fundamental concepts in computer science are, given an array of values: Sorting Class 29 Introduction two of the most fundamental concepts in computer science are, given an array of values: search through the values to see if a specific value is present and, if so, where sort

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

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING INPUT AND OUTPUT Input devices Keyboard Mouse Hard drive Network Digital camera Microphone Output devices.

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

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7) Array Basics: Outline Arrays (Savitch, Chapter 7) TOPICS Array Basics Arrays in Classes and Methods Programming with Arrays Searching and Sorting Arrays Multi-Dimensional Arrays Static Variables and Constants

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

New Concepts. Lab 7 Using Arrays, an Introduction

New Concepts. Lab 7 Using Arrays, an Introduction Lab 7 Using Arrays, an Introduction New Concepts Grading: This lab requires the use of the grading sheet for responses that must be checked by your instructor (marked as Question) AND the submission of

More information

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015 Announcements Assignment 2 posted and due on 30 th of May (23:30). Extra class tomorrow

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

Introduction to Software Development (ISD) David Weston and Igor Razgon

Introduction to Software Development (ISD) David Weston and Igor Razgon Introduction to Software Development (ISD) David Weston and Igor Razgon Autumn term 2013 Course book The primary book supporting the ISD module is: Java for Everyone, by Cay Horstmann, 2nd Edition, Wiley,

More information