Arrays. Array Basics. Chapter 8 Spring 2017, CSUS. Chapter 8.1

Similar documents
Chapter 6: Arrays. Starting Out with Games and Graphics in C++ Second Edition. by Tony Gaddis

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Repetition Structures

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

A Beginner s Guide to Programming Logic, Introductory. Chapter 6 Arrays

CS 302 ALGORITHMS AND DATA STRUCTURES

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

11 Data Structures Foundations of Computer Science Cengage Learning

7 Arrays. 7.1 Arrays Hold Multiple Values TOPICS. CONCEPT: An array allows you to store and work with multiple values of the same data type.

Programming Logic and Design Sixth Edition

Pseudocode. ARITHMETIC OPERATORS: In pseudocode arithmetic operators are used to perform arithmetic operations. These operators are listed below:

DATA STRUCTURES USING C

Lecture Outline. Rainfall Solution Attempt 1. Motivation for arrays. Introducing the Array. Motivation

Chapter 9 Introduction to Arrays. Fundamentals of Java

REPETITION CONTROL STRUCTURE LOGO

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Class C{ int a; } what variables below are objects : a. C c; b. String str; c. Scanner scanner; d. int num; e. float f;

DECISION CONTROL AND LOOPING STATEMENTS

Understanding the problem

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

Introduction to Programming

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

CS450 - Structure of Higher Level Languages

Pointers in C/C++ 1 Memory Addresses 2

Arrays. CSE / ENGR 142 Programming I. Chapter 8. Another Motivation - Averaging Grades. Motivation: Sorting. Data Structures.

CS 302: Introduction to Programming in Java. Lecture 9

STUDENT LESSON A12 Iterations

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

Data Structure. Chapter 11. Objectives After studying this chapter, students should be able to: 11-1 ARRAYS

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

CSC 337. JavaScript Object Notation (JSON) Rick Mercer

Objectives/Outcomes. Introduction: If we have a set "collection" of fruits : Banana, Apple and Grapes.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Arrays. CSE 142 Programming I. Chapter 8. Another Motivation - Averaging Grades. Motivation: Sorting. Data Structures. Arrays

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Introduction to Computer Science Midterm 3 Fall, Points

PASCAL. PASCAL, like BASIC, is a computer language. However, PASCAL, unlike BASIC, is a Blocked Structured Language (BASIC is known as unstructured).

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

Iteration Loops. The Do While Loop (Continued) Looping Subtasks

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

Indicate the answer choice that best completes the statement or answers the question. Enter the appropriate word(s) to complete the statement.

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

University of Massachusetts Lowell

CS 101, Spring 2016 March 22nd Exam 2

Stepwise Refinement. Lecture 12 COP 3014 Spring February 2, 2017

TOPICS TO COVER:-- Array declaration and use.

Enters system mode. Example The following example creates a scheduler named maintenancesched and commits the transaction:

Example: Which of the following expressions must be an even integer if x is an integer? a. x + 5

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

CS 106 Introduction to Computer Science I

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

Start Fred Functions. Quadratic&Absolute Value Transformations. Graphing Piecewise Functions Intro. Graphing Piecewise Practice & Review

isinstance and While Loops

Session 8.2. Finding Winners Using Arrays

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Using Variables to Write Pattern Rules

Control Statements. if for while

Armstrong State University Engineering Studies MATLAB Marina Switch-Case Statements Primer

ACT! Calendar to Excel

CS 106 Introduction to Computer Science I

Chapter Goals. Contents LOOPS

Friday Four Square! Today at 4:15PM, Outside Gates

Arrays. Arizona State University 1

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Tutorial 06. Conditional statement: if then, if else, switch

4. Assignment statements Give an assignment statement that sets the value of a variable called total to 20: Answer: total = 20;

: Dimension. Lecturer: Barwick. Wednesday 03 February 2016

ARRAYS, RECURSION, AND COMPLEXITY

PLD Semester Exam Study Guide Dec. 2018

Java Programming: from the Beginning

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

1 Lexical Considerations

A Look Back at Arithmetic Operators: the Increment and Decrement

Matrices. A Matrix (This one has 2 Rows and 3 Columns) To add two matrices: add the numbers in the matching positions:

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

CS 113 PRACTICE FINAL

CS 113 MIDTERM EXAM 2 SPRING 2013

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Lecture 22. While Loops

ECE 122. Engineering Problem Solving Using Java

Binary Search and Worst-Case Analysis

Arrays in Java Multi-dimensional Arrays

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

Part 1 Your First Function

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Java Coding 3. Over & over again!

Transcription:

Arrays Chapter 8 Spring 2017, CSUS Array Basics Chapter 8.1 1

Array Basics Normally, variables only have one piece of data associated with them An array allows you to store a group of items of the same data type together in memory 1/21/2017 Sacramento State - CSc 10A 3 Array Basics Why? Instead of creating multiple similar variables such as employee1, employee2, employee3 and so on It s more efficient to create just one variable with a shared, but multiple values 1/21/2017 Sacramento State - CSc 10A 4 2

Metaphor for Arrays Think of an array as a set of mailboxes Each mailbox belongs to the same variable Each mailbox has a unique number 1/21/2017 Sacramento State - CSc 10A 5 Metaphor for Arrays... or think of arrays as a group of boxes Each box belongs to the same variable Each box has a unique number 1/21/2017 Sacramento State - CSc 10A 6 3

Array Terminology Each value located in an array is called an element Each can be accessed using an unique number called an index (also called a subscript) 1/21/2017 Sacramento State - CSc 10A 7 What Value Do We Start With? So, what are the valid values for the index? Most languages use 0-indexing other languages use 1-indexing the success of C set the standard nowadays, most major languages use 0-indexing (e.g. Visual Basic) 1/21/2017 Sacramento State - CSc 10A 8 4

Zero Indexing This means the first element in any array has the index 0 So, even though this will be odd and strange, it is something you must learn to live with 1/21/2017 Sacramento State - CSc 10A 9 Creating Arrays Chapter 8.1 5

Creating Arrays Arrays are created pretty much the same as any other variable However, since the array can contain multiple values, you must specify its size 1/21/2017 Sacramento State - CSc 10A 11 Book Pseudocode: Array Declare total number of elements Declare type name [ size ] Real, Integer, or String 1/21/2017 Sacramento State - CSc 10A 12 6

Examples Declare String employees[50] Declare Real salesamounts[7] 1/21/2017 Sacramento State - CSc 10A 13 Accessing Elements 1/21/2017 Sacramento State - CSc 10A 14 7

Array Declarations age Declare Real age[3] 0 1 2 1/21/2017 Sacramento State - CSc 10A 15 Accessing Each Cell After an array is created you can read/write any element You can also access the entire array using the variable name 1/21/2017 Sacramento State - CSc 10A 16 8

Accessing Each Cell The notation is incredibly simple Simply follow the array name by square brackets and the index of the element you want 1/21/2017 Sacramento State - CSc 10A 17 How You Access an Element Variable Name name [index] 0, 1, 2, 1/21/2017 Sacramento State - CSc 10A 18 9

Example Variables sacstate totalcost Normal variables test[4] name[2] Array elements 1/21/2017 Sacramento State - CSc 10A 19 Array Elements 1/21/2017 Sacramento State - CSc 10A 8-20 10

Array Example What Happens? Declare Integer test[2] Set test[0] = 1947 Set test[1] = 42 Display test[0] Display test[1] 1/21/2017 Sacramento State - CSc 10A 21 Array Example What Happens? Declare Integer test[2] test Set test[0] = 1947 Set test[1] = 42 0 1 1/21/2017 Sacramento State - CSc 10A 22 11

Array Example What Happens? Declare Integer test[2] Set test[0] = 1947 Set test[1] = 42 0 1 test 1947 1/21/2017 Sacramento State - CSc 10A 23 Array Example What Happens? Declare Integer test[2] Set test[0] = 1947 Set test[1] = 42 0 1 test 1947 42 1/21/2017 Sacramento State - CSc 10A 24 12

Array Example Declare Integer test[2] Set test[0] = 1947 Set test[1] = 42 Display test[0] Display test[1] 1/21/2017 Sacramento State - CSc 10A 25 Array Example Output 1947 42 1/21/2017 Sacramento State - CSc 10A 26 13

Array Initialization Just like regular variables, arrays can be initialized to 0 or specific values Not all languages support this however, the big ones such as C#, Java, and Visual Basic do even though the notation varies a bit 1/21/2017 Sacramento State - CSc 10A 8-27 Example Declare String days[7] = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" 1/21/2017 Sacramento State - CSc 10A 28 14

Bounds Checking Sometimes the program will use an invalid index Naturally, this is attempting to access data that does not exist Array bounds checking prevents the use of an invalid subscript 1/21/2017 Sacramento State - CSc 10A 8-29 Example Declare String days[7] days[7] = "Saturday" Invalid because there is no 7 index 1/21/2017 Sacramento State - CSc 10A 30 15

Bounds Checking A common error is running a loop one time more than is necessary, exceeding the bound of the array This is an off-by-one error and is happens quite often (especially so because we use 0-indexing) 1/21/2017 Sacramento State - CSc 10A 8-31 Loops and Arrays Chapter 8.1 16

For Loops and Arrays For Loops are extremely well suited for iterating through all the values of an array In fact, one of the reasons For Loops exists is to interact with arrays 1/21/2017 Sacramento State - CSc 10A 33 Loops and Arrays Using For Loops, it is easy to access all the elements of an array linearly The loop variable is used as the index in the array 1/21/2017 Sacramento State - CSc 10A 34 17

Declare String name[4] Declare Integer n name[0] = "Tappa Kegga Bru" name[1] = "Cuppa Kappa Chino" name[2] = "Hu Delta Phart" name[3] = "Eta Lotta Pi" For n = 0 TO 3 Display name[n] End For 1/21/2017 Sacramento State - CSc 10A 35 Greek Example Output Tappa Kegga Bru Cuppa Kappa Chino Hu Delta Phart Eta Lotta Pi 1/21/2017 Sacramento State - CSc 10A 36 18

Loop Example Declare Integer n Declare String days[7] = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" For n = 0 to 6 Display days[n] End For 1/21/2017 Sacramento State - CSc 10A 37 Loop Example Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday 1/21/2017 Sacramento State - CSc 10A 38 19

Loop Example 2 Declare Integer n Declare String days[7] = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" For n = 0 to 6 Display n, days[n] End For 1/21/2017 Sacramento State - CSc 10A 39 Loop Example 2 Output 0 Sunday 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday 1/21/2017 Sacramento State - CSc 10A 40 20

Declare Real score[3] Set score[0] = 85 Set score[1] = 98 Set score[2] = 61 For n = 0 to 2 If score[n] >= 70 Then Display score[n], " passes" Else Display score[n], " fails" End If End For 1/21/2017 Sacramento State - CSc 10A 41 Array Example 2 Output 85 passes 98 passes 61 fails 1/21/2017 Sacramento State - CSc 10A 42 21

The For Each Loop Some languages provide a For Each loop It works with an array, iterating once for each array element During each iteration, the loop copies an element's value to a variable. 1/21/2017 Sacramento State - CSc 10A 8-43 For Each Example Constant Integer SIZE = 4 Declare Integer numbers[size] = 5, 10, 15, 20 Declare Integer num For Each num In numbers Display num End For 1/21/2017 Sacramento State - CSc 10A 44 22

Partially Filled Array Chapter 8.1 Partially Filled Array Sometimes an array is only partially filled To avoid processing the unfilled elements, you must use an integer variable that holds the number of items stored in the array 1/21/2017 Sacramento State - CSc 10A 46 23

Partially Filled Array When the array is empty, 0 is stored in this variable The variable is incremented each time an item is added to the array The variable's value is used as the array's size when stepping through the array. 1/21/2017 Sacramento State - CSc 10A 8-47 Declare Real score[100] Declare Integer Count 100 Capacity Display "How many tests?" Input Count Not using all of it For n = 0 to Count - 1 End For Input score[n] 1/21/2017 Sacramento State - CSc 10A 48 24

Array Example 2 Output How many tests? 3 65 89 77 1/21/2017 Sacramento State - CSc 10A 49 Sequentially Searching an Array Chapter 8.2 25

Sequentially Searching an Array A sequential search algorithm is a simple technique for finding an item in a string or numeric array One of the most common and ways of locating data 1/21/2017 Sacramento State - CSc 10A 8-51 How it Works Uses a loop to sequentially step through an array Compares each element with the value being searched for Stops when the value is found or the end of the array is hit 1/21/2017 Sacramento State - CSc 10A 52 26

Example Set found = False Set index = 0 While not found AND index <= SIZE - 1 If array[index] == searchvalue Then Set found = True Else End if found Set index = index + 1 End If End While If not, look at next item (next index) 1/21/2017 Sacramento State - CSc 10A 53 Processing the Contents of an Array Chapter 8.3 27

Processing the Contents of an Array It is common to use an array to store multiple values to be analyzed The information is first stored, and then analyzed later by a different loop 1/21/2017 Sacramento State - CSc 10A 8-55 Calculating the Average Loops are used to accumulate the values create a total Then, the total is simply divided by the size 1/21/2017 Sacramento State - CSc 10A 8-56 28

Calculate the Average Set total = 0 For n = 0 to SIZE 1 total = total + score[n] End For Set average = total / SIZE 1/21/2017 Sacramento State - CSc 10A 57 Highest and Lowest Value Finding the highest & lowest values in an array is common It basically works by scanning the array and setting a high (or low value) based on the current value 1/21/2017 Sacramento State - CSc 10A 8-58 29

Steps Involved Highest Value Create a variable to hold the highest value Assign the value at element 0 to the highest Use a loop to step through the rest of the elements Each iteration, a comparison is made to the highest variable If the element is greater than the highest value, that value is then the assigned to the highest variable 1/21/2017 Sacramento State - CSc 10A 8-59 Highest Value Set highest = scores[0] For n = 1 to count 1 If score[n] > highest Set highest = score[n] End if End For 1/21/2017 Sacramento State - CSc 10A 60 30

Lowest Value Set lowest = scores[0] For n = 1 to count 1 if score[n] < lowest Set lowest = score[n] end if End For 1/21/2017 Sacramento State - CSc 10A 61 Example 2 The following is a full program that uses many of the techniques we covered arrays counter for partially filled arrays sentinel loops and more So, if you understand this program, then you understand the material 1/21/2017 Sacramento State - CSc 10A 62 31

Constant Integer SIZE = 100 Declare Integer values[size] Declare Integer count = 0 Declare Integer number Declare Integer Index Display "Enter a number, or -1 to quit." Input number While (number!= -1 AND count < SIZE) Set values[count] = number Set count = count + 1 Display "Enter a number, or -1 to quit." Input number End While Display "Here are the values you entered:" For index = 0 To count - 1 Display values[index] End For 1/21/2017 Sacramento State - CSc 10A 8-63 Parallel Arrays Chapter 8.4 32

Parallel Arrays Often more than one piece of information needs to be saved for the same "object" One common approach is to use multiple arrays one for each type of data 1/21/2017 Sacramento State - CSc 10A 65 Parallel Arrays These are called parallel arrays They are separate arrays but we used the same index for each By using the same index, we can establish a relationship between them 1/21/2017 Sacramento State - CSc 10A 66 33

Parallel Arrays 1/21/2017 Sacramento State - CSc 10A 8-67 Example: Part 1 Input Constant SIZE = 10 Declare String name[size] Declare Real cash[size] For n = 0 to SIZE 1 Input name[n] Input cash[n] End For 1/21/2017 Sacramento State - CSc 10A 68 34

Example: Part 2 Search Set best = 0 For n = 1 to SIZE 1 If cash[n] > cash[best] Set best = n End If End For 1/21/2017 Sacramento State - CSc 10A 69 Example: Part 3 Results Display name[highest], Display "got the most donations of $", cash[best] 1/21/2017 Sacramento State - CSc 10A 70 35

Example Output Tappa Kegga Bru 32.23 Lambda Lambda Lambda 432.11 Eta Lotta Pi 54.25 Lambda Lambda Lambda got the most donations of $432.11 1/21/2017 Sacramento State - CSc 10A 71 Two Dimension Arrays Chapter 8.5 36

Two Dimension Arrays A two-dimensional array is like several identical arrays put together Suppose a teacher has six students who take five tests 1/21/2017 Sacramento State - CSc 10A 73 Two-Dimensional Arrays 1/21/2017 Sacramento State - CSc 10A 8-74 37

Multiple Sizes Needed Two size variables are required when declaring two dimensional arrays Accessing is done with two loops, and both indexes 1/21/2017 Sacramento State - CSc 10A 75 Declaring Arrays Constant Integer ROWS = 3 Constant Integer COLS = 4 Declare Integer values[rows][cols] 1/21/2017 Sacramento State - CSc 10A 76 38

Using Loops For row = 0 To ROWS -1 For col = 0 To COLS 1 Display "Enter a number." Input values[row][col] End For End For 1/21/2017 Sacramento State - CSc 10A 77 Arrays of Three or More Dimensions Chapter 8.6 39

Arrays of Three or More Dimensions Arrays can also be three or more dimensions In fact, there are no limitations once the number of dimensions 1/21/2017 Sacramento State - CSc 10A 79 Arrays of Three or More Dimensions Declare Real seats[3][5][8] 1/21/2017 Sacramento State - CSc 10A 8-80 40

Arrays of Three or More Dimensions 1/21/2017 Sacramento State - CSc 10A 81 41