Understanding Arrays and How They Occupy Computer Memory

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Programming with Microsoft Visual Basic th Edition
Programming Logic and Design, Third Edition Comprehensive
Programming Logic and Design Eighth Edition
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Programming Logic and Design Sixth Edition
Arrays.
Programming Logic and Design, Third Edition Comprehensive
Objectives In this chapter, you will learn about:
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 6 Control Structures.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
An Object-Oriented Approach to Programming Logic and Design Chapter 6 Looping.
C++ for Engineers and Scientists Third Edition
An Object-Oriented Approach to Programming Logic and Design Chapter 7 Arrays.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
Programming Logic and Design, Third Edition Comprehensive
 Pearson Education, Inc. All rights reserved Arrays.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 8: String Manipulation
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Processing Arrays Lesson 8 McManusCOP Overview One-Dimensional Arrays –Entering Data into an Array –Printing an Array –Accumulating the elements.
Programming Logic and Design, Second Edition, Comprehensive
Array Processing Simple Program Design Third Edition A Step-by-Step Approach 7.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Programming Logic and Design Fifth Edition, Comprehensive
Array Processing.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays.
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
Neal Stublen Computer Memory (Simplified)  Remember, all programming decisions came down to a true or false evaluation  Consider.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Chapter 12: String Manipulation Introduction to Programming with C++ Fourth Edition.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Processing Arrays Lesson 9 McManusCOP Overview One-Dimensional Arrays –Entering Data into an Array –Printing an Array –Accumulating the elements.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Programming with Microsoft Visual Basic 2012 Chapter 9: Arrays.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
REPETITION CONTROL STRUCTURE
User-Defined Functions
Arrays, For loop While loop Do while loop
EKT150 : Computer Programming
Starting Out with Programming Logic & Design
Chapter 7: User-Defined Functions II
Programming Logic and Design Fifth Edition, Comprehensive
Presentation transcript:

Understanding Arrays and How They Occupy Computer Memory A sequenced collection of elements of the same data type is called array Series or list of variables in computer memory All variables share the same name but with different index Each variable has a different subscript Element Each item in array is called element. Array

How Arrays Occupy Computer Memory Subscript (or index) Position number of an item in an array Subscripts are always a sequence of integers Array elements are contiguous in memory Size of the array: number of elements it will hold Array

How Arrays Occupy Computer Memory (continued) Figure 6-1 Appearance of a three-element array in computer memory Array

How Arrays Occupy Computer Memory (continued) 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 Array

Declaration & Initialization of Array Syntax in C to declare an array datatype Name[size]; Example int subjectMark[7]; In C language index start with the value 0 int count[3]; It will declare 6 variable named with count and can be accessed by count[0],count[1],count[2] Example of declaration with initialization int count[6]={0}; It will initialize the each variable of the array with the value 0 Array

Declaration & Initialization of Array(continued) int count[6]={1,2}; It will initialize the first element with the value 1 which have the index 0; Example: int num[3]; First value is stored on index 0 scanf(“%d”,&num[0]); String is a series of characters treated as a unit. char name[4]=“FOP”; Name is a string having size 4 F O P \0 Array

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 Array

Figure 6-3 Flowchart and pseudocode of decision-making process using a series of decisions—the hard way Array

Manipulating an Array to Replace Nested Decisions (continued) 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 Array

Figure 6-4 Flowchart and pseudocode of decision-making process—but still the hard way Array

Figure 6-5 Flowchart and pseudocode of decision-making process using an array—but still a hard way

Code Replacing the nested structure int main(){ int dep,i,count[6]={0}; printf(“Give the Number of dependent:”); scanf(“%d”,&dep);//Prime read while(dep>=0&&dep<6) { count[dep]=count[dep]+1; scanf(“%d”,&dep); } for(i=0;i<6;i++) printf(“No of employee having %d child=%d”,i,count[i]); }return 0; Array

Variable & Constant Arrays When the value of the array element is changed during the execution time is called variable array. When the array value is assigned at the coding time which is permanent and final is called constant array. Example: int FloorRent[4]={350,400,600,100}; Floor Rent 350 1 400 2 600 3 1000 Array

//code to make a list with rent //code to make a list with rent. Single line comment int main(){ char name[20]; int floor; const intFloorRent[4]={350,400,600,100}; printf(“Give the floor number & name”); scanf(“%d”,&floor); scanf(“%s”,name); while(floor>=0 && floor<4) { printf(“Name:%s,Rent=%d”,Name,FloorRent[floor]); } return 0; Array

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] Array

Searching an Array Sometimes must search through an array to find a value Example: Class numbers are three-digit, non-consecutive numbers Faculty enters class number, check if class number is valid Create an array that holds valid class numbers Search array for exact match Array

int main() { int class,i=0,flag=0,ClassCode[5]={102,203,101,203,104}; printf(“Enter class number:”); scanf(“%d”,&class); while(i<5) if(ClassCode[i]==class) flag=1; } i++; if(flag==1) printf(“Correct class”); else printf(“Incorrect class”); Array

Searching an Array (continued) 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 Array

Using Parallel Arrays Example: studentId-mark Parallel arrays Two arrays, each with sixty elements Valid student id [1,2,3,…,60] Valid marks [ 0-50 ] 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 Array

Figure 6-9 Parallel arrays studId 1 2 3 4 5 Marks 20 44 33 22 11 Figure 6-9 Parallel arrays Array

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 Array

/. Program to store student data in parallel array /*Program to store student data in parallel array. Here studId[5],marks[5] are parallel array. Array using for loop. */ int main() { int studId[5],marks[5],i; for(i=0;i<5;i++) scanf(“%d”,&studId[i]); scanf(“%d”,&marks[i]); } return 0; Array

Improving Search Efficiency Program should stop searching the array when a match is found The larger the array, the better the improvement by doing an early exit Array

int class,i=0,flag=0,ClassCode[5]={102,203,101,203,104}; int main() { int class,i=0,flag=0,ClassCode[5]={102,203,101,203,104}; printf(“Enter class number:”); scanf(“%d”,&class); while(i<5 && flag==0) if(ClassCode[i]==class) flag=1; } i++; if(flag==1) printf(“Correct class”); else printf(“Incorrect class”); Array

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 Array

Searching an Array for a Range Match (continued) Figure 6-13 Usable—but inefficient—discount array Array

Searching an Array for a Range Match (continued) Drawbacks of first approach Requires very large array with the use a lot of memory Stores same value repeatedly Difficult to know the no of elements Customer can order more Better approach Create four discount array elements for each discount rate Parallel array with discount range Array

Searching an Array for a Range Match (continued) Figure 6-14 Parallel arrays to use for determining discount Array

Psuedo code determines discount rate start num quantity,x num SIZE=4 num Discount[SIZE]=0,0.10,0.15,0.20 num Discount_Range[SIZE]=0,9,13,26 get quantity x=SIZE-1 while quantity<Discount_Range[x] x=x-1 endwhile print “Discount rate:”,Discount[x] stop Array

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 Array

Figure : Determining the month string from user’s numeric entry Array

Remaining within Array Bounds (continued) 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 Array

start num month num Max_Month=12 String Month_Name[Max_Month]=“January”, February”, ”March”, ”April”, ”May”, ”June”, ”July”, ”August”, September”, ”October”, ”November”, ”December” get month if month>=1 AND month<=Max_Month then month=month-1 print Month_Name[month] else print “Invalid month” endif stop Array

start num month num Max_Month=12 String Month_Name[Max_Month]=“January”, February”, ”March”, ”April”, ”May”, ”June”, ”July”, ”August”, September”, ”October”, ”November”, ”December” get month while month<1 OR month>Max_Month print “Invalid month” endwhile month=month-1 print Month_Name[month] stop Array

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 Array

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 Array

Summary (continued) 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 Array

Summary (continued) 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 Array