COMP 110 Introduction to Programming. What did we discuss?

Similar documents
Arrays and while Loops. Lecture 15 - COMP110 - Spring 2018

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

COMP 110 Introduction to Programming. What did we discuss?

COMP 110 Introduction to Programming. What did we discuss?

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

COMP 110 Introduction to Programming. What did we discuss?

Objectives. Order (sort) the elements of an array Search an array for a particular item Define, use multidimensional array

Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

Arrays. Lecture 11 CGS 3416 Spring March 6, Lecture 11CGS 3416 Spring 2017 Arrays March 6, / 19

COMP 110 Introduction to Programming. What did we discuss?

St. Edmund Preparatory High School Brooklyn, NY

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Introduction to Object-Oriented Programming

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Last Class. While loops Infinite loops Loop counters Iterations

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Example: Computing prime numbers

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)

Lecture 14. 'for' loops and Arrays

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

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

Array Basics: Outline

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

Fundamentals of Programming Data Types & Methods

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

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

Object Oriented Programming. Java-Lecture 6 - Arrays

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

Top-Down Program Development

CS 101 Spring 2007 Midterm 2 Name: ID:

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Session 8.2. Finding Winners Using Arrays

array Indexed same type

Arrays Chapter 6 Chapter 6 1

Array. Array Declaration:

CS S-08 Arrays and Midterm Review 1

CIS 110 Fall 2016 Introduction to Computer Programming 13 Oct 2016 Midterm Exam Answer Key

Arrays. Fundamentals of Computer Science

Over and Over Again GEEN163

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

Static Methods. Why use methods?

CS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15)

LAB 12: ARRAYS (ONE DIMINSION)

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

Lesson 10: Quiz #1 and Getting User Input (W03D2)

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

4. Java language basics: Function. Minhaeng Lee

Arrays. Loops + arrays: challenge problem. Arrays (II) An array is a set of variables of the same type accessed by their index.

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

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Java Coding 3. Over & over again!

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

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

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Arrays CHAPTER. 6.1 INTRODUCTION TO ARRAYS 338 Creating and Accessing Arrays 339 The length Instance Variable 342 Initializing Arrays 345

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

Arrays. CS Feb 2008

Array Basics: Outline

COMP 110/L Lecture 13. Kyle Dewey

Java Programming: from the Beginning

7. Arrays, More Java Looping

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Chapter 4: Conditionals and Recursion

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

CIS 110 Fall 2016 Introduction to Computer Programming 13 Oct 2016 Midterm Exam

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

Pointers in C/C++ 1 Memory Addresses 2

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

AP Computer Science Unit 1. Programs

Chapter 11 Introduction to Programming in C

Spring 2013 COMP Midterm Exam Solutions March 07, 2013

Module 5. Arrays. Adapted from Absolute Java, Rose Williams, Binghamton University

C++ for Java Programmers

Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221

CS61C : Machine Structures

Arrays. Eng. Mohammed Abdualal

4. Java Project Design, Input Methods

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

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

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

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

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

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Repetition, Looping. While Loop

Chapter 11 Introduction to Programming in C

CSE 114 Computer Science I

Topic 21 arrays - part 1

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

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

Ch. 6. User-Defined Methods

Controls Structure for Repetition

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

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

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:

Chapter 11 Introduction to Programming in C

Transcription:

COMP 110 Introduction to Programming Fall 2015 Time: TR 9:30 10:45 Room: AR 121 (Hanes Art Center) Jay Aikat FB 314, aikat@cs.unc.edu Previous Class What did we discuss? 1

Today Announcements Assignment 2 : Due Friday, Oct 2 @ 11:55 PM http://comp110.com/assignments/the worried wizard Midterm on Thu, Oct 8 in class, no computers Study guide http://comp110.com/midterm study guide Arrays Let s talk Dorms 2

Proposal: Krzyzewski Dorm Mike Krzyzewski will donate a lot of money to UNC iff: In Coach K Dorm, the rooms aren t numbered, they re named. Erudite Elephant Silly Snake Loud Liger Ornery Onyx Fuzzy Frog Healthy Hippo Tall Turtle Petite Pig Creepy Cat Robust Ram Melodic Monkey What benefits do room numbers provide? Everett Dorm: What are the benefits of a Dorm Name + Number Addressing Scheme? 219 201 202 203 204 205 206 207 208 209 210 211 Naming is hard. Numbering is easy. Learning and remembering names even harder. Locate rooms quickly and predictably. Easier to manage A LOT of rooms. Ok, I ll prep rooms 1 150, you prep 151 300. 3

Arrays are like Dorms for Data 219 01 02 03 04 05 06 07 08 09 10 11 int int int int int int int int int int int 0 1 2 3 4 5 6 7 8 9 10 (Not drawn to scale.) Arrays provide uniform housing for many values. int int int int int int int int int int 1. Each room in an array is called an Element 2. An element stores a single value. No roommates! 3. All elements in an array are of the same type 4. Arrays cannot be resized after construction 4

Elements are addressed by Name and Index int int int int int int int int int int 0 1 2 3 4 5 6 7 8 9 1. Notation: arrayname[index], i.e. arrayname[9] 2. Indexing starts at [0] (not [1]) (Beware: Off by one bugs can be stingers.) Questions? Where have we seen []s? 5

Let s demystify some magic public static void main(string[] args) When you see [brackets] there are arrays This is an array of strings available to our program! What s in it? Arguments passed in when we run our program > java cli.commandlinedemo foo bar baz 0 1 2 Recall Expressions: 6

This is a major coup. Operation Form Example Read Element arrayname[index] scores[0] Accessing Elements with an Index index is any integer expression. Number arrayname[0] Integer int i = 0; arrayname[i] Arithmetic int i = 0; arrayname[i+1] Looping with an Integer for(int i = 0; i<arrayname.length; i++){ System.out.println(arrayName[i]); } 7

Operation Form Example # of Elements arrayname.length scores.length Finding # of Elements.length property is number of elements in array. Use < a.length in for loop termination test. How might we calculate Mack s Average Yardage? 8

How do we make our own arrays? Declare an Array int[] yards; PC Construct an Array yards = new int[3]; Assign Elements yards[0] = 10; yards[1] = 20; yards[2] = 30; yards int[] 10 20 30 0 1 2 How do we average yards? Java Array Operations Operation Form Example # of Elements arrayname.length scores.length Read Element arrayname[index] scores[0] Declare type[] arrayname; int[] scores; Construct arrayname = new type[size]; scores = new int[3]; Assign Element arrayname[index] = expression; scores[0] = 12; Initialize (Just a shortcut.) type[] arrayname = {elements}; int[] scores = {12,0,1}; 9

Key Concepts 1) An array is a uniform structure housing many elements. 0 1 2 3 4 5 6 7 2) Elements are addressed via name and index. myarray[0] 3) Index is an expression!!! int length = 8; myarray[length 1] Arrays To think about arrays, let s think about loops first Why do we need loops? Because we want to repeat things without writing them again and again 10

Average Score without Loops Assuming that we only need 5 basketball scores for averaging int score1 = keyboard.nextint(); int score2 = keyboard.nextint(); int score3 = keyboard.nextint(); int score4 = keyboard.nextint(); int score5 = keyboard.nextint(); double average = (double) (score1 + score2 + score3 + score4 + score5) / 5.0; Average Score with Loops Assuming that we only need 5 scores for (int i = 0; i < 5; i++) scoresum += keyboard.nextint(); double average = (double) scoresum / 5.0; 11

What if we really need to save them If we really need to save these scores, loop won t help you Think about this problem Print out if a score is above/below average We have to calculate average first, then decide if a score is above/below average Therefore we must save all these scores, and compare them to the average in the end Comparing All Scores and the Average System.out.println("Enter 5 basketball scores:"); Scanner keyboard = new Scanner(System.in); int score1 = keyboard.nextint(); int score2 = keyboard.nextint(); int score3 = keyboard.nextint(); int score4 = keyboard.nextint(); int score5 = keyboard.nextint(); double average = (double) (score1 + score2 + score3 + score4 + score5) / 5.0; System.out.println("Average score: " + average); // repeat this for each of the 5 scores if (score1 > average) System.out.println(score1 + ": above average"); else if (score1 < average) System.out.println(score1 + ": below average"); else System.out.println(score1 + ": equal to the average"); // if score2...score3...score4... 12

If we have more Scores Think about 80 scores Declare 80 variables Check them 80 times This is illogical! There must be an easier way! What about things like: Score 1, Score 2,, Score n Arrays int[] scores = new int[5]; This is like declaring 5 strangely named variables of type int: scores[0] scores[1] scores[2] scores[3] scores[4] Especially, you can use score[i] to locate a single one 13

Arrays An array is a collection of items of the same type Like a list of different variables, but with a nice, compact way to name them A special kind of object in Java Loops repeat things temporally; arrays repeat things spatially Comparing Scores/Averages w/ Arrays System.out.println("Enter 5 basketball scores:"); Scanner keyboard = new Scanner(System.in); int[] scores = new int[5]; int scoresum = 0; for (int i = 0; i < 5; i++) { scores[i] = keyboard.nextint(); scoresum += scores[i]; } double average = (double) scoresum / 5; System.out.println("Average score: " + average); for (int i = 0; i < 5; i++) { if (scores[i] > average) System.out.println(scores[i] + ": above average"); else if (scores[i] < average) System.out.println(scores[i] + ": below average"); else System.out.println(scores[i] + ": equal to the average"); } 14

Index Variables such as scores[0] and scores[1] that have an integer expression in square brackets are known as: indexed variables, subscripted variables, array elements, or simply elements An index or subscript is an integer expression inside the square brackets that indicates an array element ArrayName[index] Index Where have we seen the word index before? String s indexof() method H o w a r e y o u? 0 1 2 3 4 5 6 7 8 9 10 11 str.indexof( e ) == 6; str.charat(6) == e ; 15

Index Index numbers start with 0. They do NOT start with 1 or any other number. Not like counters in loops, you can t change the range of indices The reason is that the array name represents a memory address, and the i th element can be accessed by the address plus i Array and Index var name score[0] score[1] score[2] score[3] score[4] data 62 51 88 70 74 m address 25131 25132 25133 25134 25135 score score+1 score+2 In history, computer scientists argued a lot on this Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration. Stan Kelly Bootle 16

Access Elements with Indices The number inside square brackets can be any integer expression An integer: scores[3] Variable of type int: scores[index] Expression that evaluates to int: scores[index*3] Can use elements just like any other variables: scores[3] = 68; scores[4] = scores[4] + 3; // just made a 3 pointer! System.out.println(scores[1]); Indices and For-Loops In programming, a for loop usually starts with counter i = 0. There is a reason for (int i = 0; i < 5; i++) { scores[i] = keyboard.nextint(); scoresum += scores[i]; } 17

Creating an Array Array is a special class and we create its objects Syntax for creating an array: Base_Type[] Array_Name = new Base_Type[Length]; Example: int[] pressure = new int[100]; Alternatively: int[] pressure; pressure = new int[100]; Do not be OUT OF BOUNDS! Indices MUST be in bounds double[] entries = new double[5]; // from [0] to [4] entries[5] = 3.7; // ERROR! Index out of bounds Your code will compile if you are using an index that is out of bounds, but it will give you a run time error! 18

Initializing Arrays You can initialize arrays when you declare them int[] scores = { 68, 97, 102 }; Equivalent to int[] scores = new int[3]; scores[0] = 68; scores[1] = 97; scores[2] = 102; Or, you can use for loop When in doubt, for loop! Joke Q: Why did the programmer quit his job? A: Because he didn't get arrays. Hint: A raise ; ) 19

Next class More on arrays 20