Programming Logic and Design Sixth Edition

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

Example. Section: PS 709 Examples of Calculations of Reduced Hours of Work Last Revised: February 2017 Last Reviewed: February 2017 Next Review:

Sequential Search (Searching Supplement: 1-2)

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

numbers by multi-digit whole numbers by using strategies based on place value, the properties of operations and the relationship between

Arrays. Arrays (8.1) Arrays. One variable that can store a group of values of the same type. Storing a number of related values.

JAVASCRIPT LOOPS. Date: 13/05/2012 Page: 1 Total Chars: 4973 Total Words: 967

MAP OF OUR REGION. About

DATE OF BIRTH SORTING (DBSORT)

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

Arrays. What if you have a 1000 line file? Arrays

MAP OF OUR REGION. About

Tutorial 8 (Array I)

CONDITIONAL EXECUTION: PART 2

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Read and fill in this page now. Your lab section day and time: Name of the person sitting to your left: Name of the person sitting to your right:

Condi(onals and Loops

Computer Grade 5. Unit: 1, 2 & 3 Total Periods 38 Lab 10 Months: April and May

CHAPTER 5 FLOW OF CONTROL

INTENT TO FILE (ITF)

Chapter 4 - Notes Control Structures I (Selection)

Unit Title Key Concepts Vocabulary CCS

HPE Secur & HPE Secur Cloud

Special Education Room and Board Reimbursement Claim User Guide

MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY

A Beginner s Guide to Programming Logic, Introductory. Chapter 5 Looping

ITT8060: Advanced Programming (in F#)

Difference Between Dates Case Study 2002 M. J. Clancy and M. C. Linn

Stat 428 Autumn 2006 Homework 2 Solutions

Analysis/Intelligence: Data Model - Configuration

Programming Logic and Design Sixth Edition

Lecture-14 Lookup Functions

Marketing Opportunities

Cursors Christian S. Jensen, Richard T. Snodgrass, and T. Y. Cliff Leung

Maryland Soybeans: Historical Basis and Price Information

ADVANCED ALGORITHMS TABLE OF CONTENTS

14. Other Data Types. Compound Data Types: Defined data types (typedef) Unions typedef existing_type new_type_name ;

CPA PEP 2018 Schedule and Fees

Maryland Corn: Historical Basis and Price Information Fact Sheet 495

OBJECT ORIENTED PROGRAMMING USING C++

Year 10 OCR GCSE Computer Science (9-1)

REPETITION CONTROL STRUCTURE LOGO

PLD Semester Exam Study Guide Dec. 2018

Freedom of Information Act 2000 reference number RFI

Maryland Corn: Historical Basis and Price Information Fact Sheet 495

Strings and Arrays. Hendrik Speleers

/Internet Random Moment Sampling. STATE OF ALASKA Department of Health and Social Services Division of Public Assistance

COMPUTER TRAINING CENTER

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Software Development Techniques. December Sample Exam Marking Scheme

CHIROPRACTIC MARKETING CENTER

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

ECE 122. Engineering Problem Solving with Java

Nov 20, 2017 Page 1. Tripwire, Inc. Product Support and Discontinuation Policy November 2017

EECS2030 Fall 2016 Preparation Exercise for Lab Test 2: A Birthday Book

EACH MONTH CUTTING EDGE PEER REVIEW RESEARCH ARTICLES ARE PUBLISHED

Sinusoidal Data Worksheet

ACA 1095 Reporting - Editing Multiple Employees. Selecting Employees to Edit

Guernsey Post 2013/14. Quality of Service Report

Maryland Corn: Historical Basis and Price Information

COMPUTER ARCHITECTURE AND ORGANIZATION. Operation Add Magnitudes Subtract Magnitudes (+A) + ( B) + (A B) (B A) + (A B)

Dictionaries. By- Neha Tyagi PGT CS KV 5 Jaipur II Shift Jaipur Region. Based on CBSE Curriculum Class -11. Neha Tyagi, KV 5 Jaipur II Shift

Key Dates Timetables: 2015/16

Unit 4 Agresso. Introduction to Desktop

Chapter 2: Using Data

Arrays and Pointers (part 2) Be extra careful with pointers!

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

hereby recognizes that Timotej Verbovsek has successfully completed the web course 3D Analysis of Surfaces and Features Using ArcGIS 10

Exercises Software Development I. 02 Algorithm Testing & Language Description Manual inspection, test plan, grammar, metasyntax notations (BNF, EBNF)

Arrays and Pointers (part 2) Be extra careful with pointers!

Apple Inc. US 6,587,904 US 6,618,785 US 6,636,914 US 6,639,918 US 6,718,497 US 6,831,928 US 6,842,805 US 6,865,632 US 6,944,705 US 6,985,981

Introduction. C provides two styles of flow control:

Hitachi-GE Nuclear Energy, Ltd. UK ABWR GENERIC DESIGN ASSESSMENT Resolution Plan for RO-ABWR-0027 Hardwired Back Up System

Grade 7 Math LESSON 14: MORE PROBLEMS INVOLVING REAL NUMBERS TEACHING GUIDE

Chapter 7 : Arrays (pp )

Overview. Introduction. Introduction XML XML. Lecture 16 Introduction to XML. Boriana Koleva Room: C54

Read and fill in this page now. Your instructional login (e.g., cs3-ab): Your lab section days and time: Name of the person sitting to your left:

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

Lecture Transcript While and Do While Statements in C++

Advanced Syllabus 2007 Release Plan

AMS API Modifications

44 Tricks with the 4mat Procedure

MRCPI General Medicine Calendar

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

Reverse Segmentable GainMaker Node OIB Shorting Condition Technical Bulletin

Case3:12-cv VC Document32 Filed02/11/15 Page1 of 5 UNITED STATES DISTRICT COURT NORTHERN DISTRICT OF CALIFORNIA SAN FRANCISCO DIVISION

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

1 Pointer Concepts. 1.1 Pointer Examples

Software Testing. 1. Testing is the process of demonstrating that errors are not present.

MRCPI General Medicine Calendar

CS Programming I: Arrays

Chapter 6 Reacting to Player Input

Calendar Excel Template User Guide

Release Notes LAW PreDiscovery, Version Enhancements Resolved Issues Current Issues Release Information

Scheduling. Scheduling Tasks At Creation Time CHAPTER

Transcription:

Objectives Programming Logic and Design Sixth Edition Chapter 6 Arrays In this chapter, you will learn about: Arrays and how they occupy computer memory Manipulating an array to replace nested decisions Using constants with arrays Searching an array Using parallel arrays Programming Logic & Design, Sixth Edition 2 Objectives Searching an array for a range match Remaining within array bounds Using a for loop to process arrays Understanding Arrays and How They Occupy Computer Memory Array Series or list of variables in computer memory All variables share the same name Each variable has a different subscript Subscript (or index) Position number of an item in an array Subscripts are always a sequence of integers Programming Logic & Design, Sixth Edition 3 Programming Logic & Design, Sixth Edition 4 How Arrays Occupy Computer Memory Each item has same name and same data type Element: an item in the array Array elements are contiguous in memory Size of the array: number of elements it will hold How Arrays Occupy Computer Memory Figure 6-1 Appearance of a three-element array in computer memory Programming Logic & Design, Sixth Edition 5 Programming Logic & Design, Sixth Edition 6 1

How Arrays Occupy Computer Memory All elements have same group name Individual elements have unique subscript Subscript indicates distance from first element Subscripts are a sequence of integers Subscripts placed in parentheses or brackets following group name Syntax depends on programming language Manipulating an Array to Replace Nested Decisions Example: Human Resources Department Dependents report List employees who have claimed zero through five dependents Assume no employee has more than five dependents Application produces counts for dependent categories Uses series of decisions Application does not scale up to more dependents Programming Logic & Design, Sixth Edition 7 Programming Logic & Design, Sixth Edition 8 Manipulating an Array to Replace Nested Decisions Figure 6-3 Flowchart and pseudocode of decision-making process using a series of decisions the hard way Programming Logic & Design, Sixth Edition 9 Array reduces number of statements needed Six dependent count accumulators redefined as single array Variable as a subscript to the array Array subscript variable must be: Numeric with no decimal places Initialized to 0 Incremented by 1 each time the logic passes through the loop Programming Logic & Design, Sixth Edition 10 Figure 6-4 Flowchart and pseudocode of decision-making process but still the hard way Programming Logic & Design, Sixth Edition 11 Figure 6-5 Flowchart and pseudocode of decision-making process using an array but still a hard way Programming Logic & Design, Sixth Edition 12 2

Manipulating an Array to Replace Nested Decisions Figure 6-6 Flowchart and pseudocode of efficient decision-making process using an array Programming Logic & Design, Sixth Edition 13 Figure 6-7 Flowchart and pseudocode for Dependents Report program Programming Logic & Design, Sixth Edition 14 Manipulating an Array to Replace Nested Decisions Using Constants with Arrays Use constants in several ways To hold the size of an array As the array values As a subscript Figure 6-7 Flowchart and pseudocode for Dependents Report program Programming Logic & Design, Sixth Edition 15 Programming Logic & Design, Sixth Edition 16 Using a Constant as the Size of an Array Avoid magic numbers (unnamed constants) Declare a named numeric constant to be used every time array is accessed Make sure any subscript remains less than the constant value Constant created automatically in many languages Using Constants as Array Element Values Sometimes the values stored in arrays should be constants Example string MONTH[12] = "January", "February", "March", "April", "May", "June", "July", "August", "September", "October, "November", "December" Programming Logic & Design, Sixth Edition 17 Programming Logic & Design, Sixth Edition 18 3

Using a Constant as an Array Subscript Use a numeric constant as a subscript to an array Example Declare a named constant as num INDIANA = 5 Display value with: output salesarray[indiana] Searching an Array Sometimes must search through an array to find a value Example: mail-order business Item numbers are three-digit, non-consecutive numbers Customer orders an item, check if item number is valid Create an array that holds valid item numbers Search array for exact match Programming Logic & Design, Sixth Edition 19 Programming Logic & Design, Sixth Edition 20 Figure 6-8 Flowchart and pseudocode for program that verifies item availability Programming Logic & Design, Sixth Edition 21 Figure 6-8 Flowchart and pseudocode for program that verifies item availability Programming Logic & Design, Sixth Edition 22 Searching an Array Figure 6-8 Flowchart and pseudocode for program that verifies item availability Programming Logic & Design, Sixth Edition 23 Flag: variable that indicates whether an event occurred Technique for searching an array Set a subscript variable to 0 to start at the first element Initialize a flag variable to false to indicate the desired value has not been found Examine each element in the array If the value matches, set the flag to True If the value does not match, increment the subscript and examine the next array element Programming Logic & Design, Sixth Edition 24 4

Using Parallel Arrays Example: mail-order business Two arrays, each with six elements Valid item numbers Valid item prices Each price in valid item price array in same position as corresponding item in valid item number array Parallel arrays Each element in one array associated with element in same relative position in other array Look through valid item array for customer item When match is found, get price from item price array Figure 6-9 Parallel arrays in memory Programming Logic & Design, Sixth Edition 25 Programming Logic & Design, Sixth Edition 26 Using Parallel Arrays Use parallel arrays Two or more arrays contain related data A subscript relates the arrays Elements at the same position in each array are logically related Figure 6-10 Flowchart and pseudocode of program that finds an item s price using parallel arrays Programming Logic & Design, Sixth Edition 27 Programming Logic & Design, Sixth Edition 28 Figure 6-10 Flowchart and pseudocode of program that finds an item s price using parallel arrays Programming Logic & Design, Sixth Edition 29 Figure 6-10 Flowchart and pseudocode of program that finds an item s price using parallel arrays Programming Logic & Design, Sixth Edition 30 5

Improving Search Efficiency Program should stop searching the array when a match is found Setting a variable to a specific value instead of letting normal processing set it Improves efficiency The larger the array, the better the improvement by doing an early exit Figure 6-11 Flowchart and pseudocode of the module that finds item price, exiting the loop as soon as it is found Programming Logic & Design, Sixth Edition 31 Programming Logic & Design, Sixth Edition 32 Improving Search Efficiency Figure 6-11 Flowchart and pseudocode of the module that finds item price, exiting the loop as soon as it is found Programming Logic & Design, Sixth Edition 33 Searching an Array for a Range Match Sometimes programmers want to work with ranges of values in arrays Example: mail-order business Read customer order data; determine discount based on quantity ordered First approach Array with as many elements as each possible order quantity Store appropriate discount for each possible order quantity Programming Logic & Design, Sixth Edition 34 Searching an Array for a Range Match Figure 6-13 Usable but inefficient discount array Programming Logic & Design, Sixth Edition 35 Searching an Array for a Range Match Drawbacks of first approach Requires very large array; uses a lot of memory Stores same value repeatedly How do you know you have enough elements? Customer can always order more Better approach Create four discount array elements for each discount rate Parallel array with discount range Use loop to make comparisons Programming Logic & Design, Sixth Edition 36 6

Searching an Array for a Range Match Figure 6-14 Parallel arrays to use for determining discount Programming Logic & Design, Sixth Edition 37 Figure 6-15 Program that determines discount rate Programming Logic & Design, Sixth Edition 38 Remaining within Array Bounds Every array has finite size Number of elements in the array Number of bytes in the array Arrays composed of elements of same data type Elements of same data type occupy same number of bytes in memory Number of bytes in an array is always a multiple of number of array elements Access data using subscript containing a value that accesses memory occupied by the array Figure 6-16 Determining the month string from user s numeric entry Programming Logic & Design, Sixth Edition 39 Programming Logic & Design, Sixth Edition 40 Remaining within Array Bounds Program logic assumes every number entered by the user is valid When invalid subscript is used: Some languages stop execution and issue an error Other languages access a memory location outside of the array Invalid array subscript is a logical error Out of bounds: using a subscript that is not within the acceptable range for the array Program should prevent bounds errors Using a for Loop to Process Arrays for loop: single statement Initializes loop control variable Compares it to a limit Alters it for loop especially convenient when working with arrays To process every element Must stay within array bounds Highest usable subscript is one less than array size Programming Logic & Design, Sixth Edition 41 Programming Logic & Design, Sixth Edition 42 7

Using a for Loop to Process Arrays Using a for Loop to Process Arrays Figure 6-17 Pseudocode that uses a for loop to display an array of department names Figure 6-26 Pseudocode that uses a more efficient for loop to output month names Programming Logic & Design, Sixth Edition 43 Programming Logic & Design, Sixth Edition 44 Summary Array: series or list of variables in memory Same name and type Different subscript Use a variable as a subscript to the array to replace multiple nested decisions Some array values determined during program execution Other arrays have hard-coded values Summary Search an array Initialize the subscript Test each array element value in a loop Set a flag when a match is found Parallel arrays: each element in one array is associated with the element in second array Elements have same relative position For range comparisons, store either the low- or high-end value of each range Programming Logic & Design, Sixth Edition 45 Programming Logic & Design, Sixth Edition 46 Summary Access data in an array Use subscript containing a value that accesses memory occupied by the array Subscript is out of bounds if not within defined range of acceptable subscripts for loop is a convenient tool for working with arrays Process each element of an array from beginning to end Programming Logic & Design, Sixth Edition 47 8