Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8: Arrays Programming Logic and Design, Third Edition Comprehensive.

Similar presentations


Presentation on theme: "Chapter 8: Arrays Programming Logic and Design, Third Edition Comprehensive."— Presentation transcript:

1 Chapter 8: Arrays Programming Logic and Design, Third Edition Comprehensive

2 2 Objectives After studying Chapter 8, you should be able to: Understand how arrays are used Understand how arrays occupy computer memory Manipulate an array to replace nested decisions Declare and initialize an array Understand the difference between run-time and compile-time arrays

3 Programming Logic and Design, Third Edition Comprehensive3 Objectives Load array values from a file Search an array for an exact match Use parallel arrays Force subscripts to remain within array bounds Improve search efficiency by using an early exit Search an array for a range match

4 Programming Logic and Design, Third Edition Comprehensive4 Understanding Arrays An array is a series or list of variables in computer memory, all of which have the same name but are differentiated with special numbers called subscripts A subscript is a number that indicates the position of a particular item within an array Whenever you require multiple storage locations for objects, you are using a real-life counterpart of a programming array

5 Programming Logic and Design, Third Edition Comprehensive5 How Arrays Occupy Computer Memory When you declare an array, you declare a programming structure that contains multiple variables Each variable within an array has the same name and the same data type; each separate array variable is one element of the array Each array element occupies an area in memory next to, or contiguous to, the others, as shown in Figure 8-1

6 Programming Logic and Design, Third Edition Comprehensive6 How Arrays Occupy Computer Memory ( continued )

7 Programming Logic and Design, Third Edition Comprehensive7 How Arrays Occupy Computer Memory ( continued ) You indicate the number of elements an array will hold—the size of the array—when you declare the array along with your other variables All array elements have the same group name However, each individual element has a unique subscript indicating how far away it is from the first element

8 Programming Logic and Design, Third Edition Comprehensive8 Manipulating an Array to Replace Nested Decisions Consider a program that keeps statistics for a recycling drive competition at a high school The school is holding a competition between the freshman, sophomore, junior, and senior classes to see which class can collect the greatest number of aluminum cans

9 Programming Logic and Design, Third Edition Comprehensive9 Manipulating an Array to Replace Nested Decisions ( continued ) Each time a student brings in some cans, a clerk adds a record to a file in the following format, shown in Figure 8-2 below

10 Programming Logic and Design, Third Edition Comprehensive10 Flowchart and Pseudocode for Mainline Logic of the Can-Recycling Program

11 Programming Logic and Design, Third Edition Comprehensive11 The mainLoop() Module for the Recycling Program

12 Programming Logic and Design, Third Edition Comprehensive12 The finish() Module for the Recycling Program

13 Programming Logic and Design, Third Edition Comprehensive13 Modified housekeeping() Module for Can-Recycling Program

14 Programming Logic and Design, Third Edition Comprehensive14 Modified mainLoop() Module That Uses Count Array

15 Programming Logic and Design, Third Edition Comprehensive15 Manipulating an Array to Replace Nested Decisions The true benefit of using an array lies in your ability to use a variable as a subscript to the array, instead of using a constant such as 1 or 4 Notice in the mainLoop() in Figure 8-9 that within each decision, the value you are comparing to stuClass and the constant you are using as a subscript in the resulting “Yes” process, are always identical

16 Programming Logic and Design, Third Edition Comprehensive16 Modified mainLoop() Using Variable stuClass as a Subscript to the Count Array

17 Programming Logic and Design, Third Edition Comprehensive17 Modified finish() Module That Uses an Array

18 Programming Logic and Design, Third Edition Comprehensive18 Array Declaration and Initialization All declarations above have two things in common: They name the count array and indicate that there will be 30 separate numeric elements For flowcharting or pseudocode purposes, a statement such as num count[30] indicates the same thing

19 Programming Logic and Design, Third Edition Comprehensive19 Array Declaration and Initialization ( continued ) Declaring a numeric array does not necessarily set its individual elements to zero (although it does in some programming languages, such as BASIC, Visual Basic, and Java) Most programming languages allow the equivalent of num count[30] all set to 0 –you should use a statement like this when you want to initialize an array in your flowcharts or pseudocode

20 Programming Logic and Design, Third Edition Comprehensive20 Array Declaration and Initialization ( continued ) Explicitly initializing all variables is a good programming practice Assuming anything about non-initialized variable values is a dangerous practice Array elements are no exception to this rule

21 Programming Logic and Design, Third Edition Comprehensive21 Array Declaration and Initialization ( continued ) Alternately, to start all array elements with the same initial value, you can use an initialization loop within the housekeeping() module An initialization loop is a loop structure that provides initial values for every element in any array

22 Programming Logic and Design, Third Edition Comprehensive22 A housekeeping() Module Demonstrating One Method of Initializing Array Elements

23 Programming Logic and Design, Third Edition Comprehensive23 Run-Time and Compile-Time Arrays The array that you used to accumulate class counts in the can-recycling program is a run-time array or execution-time array, because –the values that you want to use—the final can counts—are created during an actual run, or execution, of the the program Some arrays are not run-time, but rather compile- time arrays –Final desired values are fixed at the beginning of the program

24 Programming Logic and Design, Third Edition Comprehensive24 Flowchart and Pseudocode for Mainline Logic of Rent Program

25 Programming Logic and Design, Third Edition Comprehensive25 Flowchart and Pseudocode for prep() Module of Rent Program

26 Programming Logic and Design, Third Edition Comprehensive26 Loading an Array From a File Writing the rent program from the previous section requires you to set values for five rent array elements within the prep() module If the rent values change frequently, it is inconvenient to have hard-coded values in your program Instead, write your program so that it loads the array rent amounts from a file –Example of a run-time array—an array that gets its values during the execution of the program

27 Programming Logic and Design, Third Edition Comprehensive27 Loading an Array From a File ( continued ) A file that contains all the rent amounts can be updated by apartment building management as frequently as needed In the prep() module in Figure 8-21, you set the variable count to 1 and read a rentRec record from the RENTFILE Each record in the RENTFILE contains just one field—a numeric rentAmt value

28 Programming Logic and Design, Third Edition Comprehensive28 Flowchart and Pseudocode for prep() Module That Reads Rent Values From an Input File

29 Programming Logic and Design, Third Edition Comprehensive29 Searching for an Exact Match in an Array Suppose you create an array with the six elements shown in Figure 8-24 If a customer orders item 307, a clerical worker can tell whether it is valid by looking down the list and verifying that 307 is a member of the list

30 Programming Logic and Design, Third Edition Comprehensive30 Searching for an Exact Match in an Array ( continued ) In a similar fashion, you can use a loop to test each validItem against the ordered item number To verify that an item number exists, set a subscript to 1 and set a flag variable to indicate that you have not yet determined whether the customer’s order is valid A flag is a variable that you set to indicate whether some event has occurred – frequently holds a True or False value

31 Programming Logic and Design, Third Edition Comprehensive31 Flowchart and Pseudocode Segments for Finding an Exact Match to a Customer Item Number

32 Programming Logic and Design, Third Edition Comprehensive32 Using Parallel Arrays Consider the mainline logic in Figure 8-27 and the ready() routine in Figure 8-28

33 Programming Logic and Design, Third Edition Comprehensive33 Using Parallel Arrays ( continued ) Two arrays are set up within the ready() module One contains six elements named validItem – All six elements are valid item numbers The other array also has six elements –These are named validItemPrice –All six elements are prices –Each price is conveniently and purposely in the same position as the corresponding item number in the other validItem array

34 Programming Logic and Design, Third Edition Comprehensive34 Using Parallel Arrays ( continued ) Two corresponding arrays such as these are parallel arrays because –each element in one array is associated with the element in the same relative position in the other array

35 Programming Logic and Design, Third Edition Comprehensive35 The ready() Module for the Price Program

36 Programming Logic and Design, Third Edition Comprehensive36 Using Parallel Arrays ( continued ) To write the getPrice() module, the general procedure is to: –read each item number, –look through each of the validItem values separately, –when a match for the custItemNo on the input record is found, pull the corresponding parallel price out of the list of validItemPrice values You must create a variable to use as a subscript for the arrays

37 Programming Logic and Design, Third Edition Comprehensive37 The getPrice() Module for the Price Program

38 Programming Logic and Design, Third Edition Comprehensive38 Remaining Within Array Bounds The getPrice() module in Figure 8-29 is not perfect The logic makes one dangerous assumption: that every customer will order a valid item number When you use a subscript value that is higher than the number of elements in an array, –some programming languages stop execution of the program and issue an error message

39 Programming Logic and Design, Third Edition Comprehensive39 Remaining Within Array Bounds ( continued ) When you use a subscript that is not within the range of acceptable subscripts, –your subscript is said to be out of bounds You can improve the price-finding program by adding a flag variable and a test to the getPrice() module You can set the flag when you find a valid item in the validItem array –After searching the array, check whether the flag has been altered, as shown in Figure 8-30

40 Programming Logic and Design, Third Edition Comprehensive40 The getPrice() Module Using the foundIt Flag

41 Programming Logic and Design, Third Edition Comprehensive41 Improving Search Efficiency Using an Early Exit The mail-order program is still somewhat inefficient Problem: if lots of customers order item 106 or 108, their price is found on the first or second pass through the loop –The program continues searching through the item array, however, until x exceeds the value 6

42 Programming Logic and Design, Third Edition Comprehensive42 Improving Search Efficiency Using an Early Exit ( continued ) Leaving a loop as soon as a match is found is called an early exit; it improves the program’s efficiency The larger the array, the more beneficial it becomes to exit the searching loop as soon as you find what you’re looking for

43 Programming Logic and Design, Third Edition Comprehensive43 The Final Version of the Price Program

44 Programming Logic and Design, Third Edition Comprehensive44 Searching an Array for a Range Match A range of values is any set of contiguous values, for example 1 through 5 You want to be able to read in a record and determine a discount percentage based on the value in the quantity field One ill-advised approach might be to set up an array with as many elements as any customer might ever order, and store the appropriate discount for each possible number, as shown in Figure 8-34

45 Programming Logic and Design, Third Edition Comprehensive45 Searching an Array for a Range Match ( continued )

46 Programming Logic and Design, Third Edition Comprehensive46 Searching an Array for a Range Match ( continued ) The previously mentioned approach has three drawbacks: –Requires a very large array that uses a lot of memory –You must store the same value repeatedly –Where do you stop adding array elements? A better approach is to create just four discount array elements, one for each of the possible discount rates, as shown in Figure 8-35

47 Programming Logic and Design, Third Edition Comprehensive47 Flowchart and Pseudocode for Discount Determination

48 Programming Logic and Design, Third Edition Comprehensive48 Summary An array is a series or list of variables in computer memory, all of which have the same name but are differentiated with special numbers called subscripts You often can use a variable as a subscript to an array, replacing multiple nested decisions An array whose values are determined during the execution of a program is a run-time array, or execution-time array

49 Programming Logic and Design, Third Edition Comprehensive49 Summary ( continued ) Your programs should ensure that subscript values do not go out of bounds, –that is, take on a value out of the range of legal subscripts When you need to compare a value to a range of values in an array, –you can store either the low- or high-end value of each range for comparison

50 Programming Logic and Design, Third Edition Comprehensive50

51 Functions A function is a self contained block of statements that perform coherent task. -Modularize a program –All variables declared inside functions are local variables Known only in function defined –Parameters Communicate information between functions Local variables Benefits of functions –Divide and conquer Manageable program development –Software reusability Use existing functions as building blocks for new programs Abstraction - hide internal details (library functions) –Avoid code repetition

52 Functions void mes(); /*function declaration */ int main() { mes(); /* function call */ printf(“hi”); } void mes() /* function definition */ { printf(“smile”); output: smile hi } Programming Logic and Design, Third Edition Comprehensive52

53 void italy(); void brazil(); int main() { printf(“I am in main”); italy(); printf(“back in main”); } void italy() { printf( “ \n I m in italy”); brazil(); } void brazil() { printf( “ \n I m in brazil”); } 53

54 Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value –Copy of argument passed to function –Changes in function do not effect original –Use when function does not need to modify argument Avoids accidental changes Call by reference –Passes original argument –Changes in function effect original –Only used with trusted functions For now, we focus on call by value

55  2000 Prentice Hall, Inc. All rights reserved. Outline 1. Function prototype (3 parameters) 2. Input values 2.1 Call function 3. Function definition Program Output 1/* Fig. 5.4: fig05_04.c 2 Finding the maximum of three integers */ 3#include 4 5int maximum( int, int, int ); /* function prototype */ 6 7int main() 8{8{ 9 int a, b, c; 10 11 printf( "Enter three integers: " ); 12 scanf( "%d%d%d", &a, &b, &c ); 13 printf( "Maximum is: %d\n", maximum( a, b, c ) ); 14 15 return 0; 16} 17 18/* Function maximum definition */ 19int maximum( int x, int y, int z ) 20{ 21 int max = x; 22 23 if ( y > max ) 24 max = y; 25 26 if ( z > max ) 27 max = z; 28 29 return max; 30}

56 Programming Logic and Design, Third Edition Comprehensive56 int calsum(int x, int y, int z); int main() { int a, b,c,sum; scanf(“%d %d %d “,&a,&b,&c); sum=calsum( a, b, c); printf(“sum=%d”, sum); } int calsum(int x, int y,int z) { int d; d= x +y +z; return(d); }

57 Here a,b,c are actual arguments when x,y,z are formal arguments. Programming Logic and Design, Third Edition Comprehensive57

58 We are familiar with how to call functions. we called function and pass something to it, which is values of variable so it is called call by value. Instead of passing value of variable,we can pass the address of variable to function. it is identify as call by reference. but before learn call by reference it is necessary to know concept of pointer. Programming Logic and Design, Third Edition Comprehensive58

59 Pointer Pointer is nothing but variable that contains address of location in memory. main() { int x = 7 ; printf( "%d\n", x ) ; /* show the value of x */ printf( "%d\n", &x ) ; /* show the address of x */ } When run, the above program might produce the following output: 7 -1073742924 where "7" is (obviously) the value of x, and "-1073742924" is the address of x,&x return address of variable(expressed as a signed decimal number). Programming Logic and Design, Third Edition Comprehensive59

60 * operator(value at address or indirection) return value of variable,& operator return address of variable and *(&i) return value of i variable : Programming Logic and Design, Third Edition Comprehensive60

61 int main() { int x =8 ; /* x is an integer with the value 7 */ int *px ; /* px is a pointer to an integer */ px = &x ; /* px gets the address of x */ *px = 8 ; /* the thing pointed to by px (x) gets the value 8 */ printf( "%d\n", x ) ; /* show the value of x */ printf( "%d\n", &x ) ; /* show the address of x */ printf( "%d\n", px ) ; /* show the value of px */ printf( "%d\n", *px ) ; /* show the value of what px points to */ } When run, the above program might produce the following output: 8 -1073742924 -1073742924 8 Programming Logic and Design, Third Edition Comprehensive61

62 Example of call by reference void swap(int *, int*) int main() { int a=10;b=20; swap(&a, &b); printf(“%d %d”,a,b); } void swap(int *x, int *y) { int t; t=*x; *x=*y; *y=t; } Programming Logic and Design, Third Edition Comprehensive62

63 Array of pointers We can declare an array as a pointer. Every element of this array can hold address of any variable. We can say that every element of this array is a pointer variable. It is same as array but it is a collection of addresses. Programming Logic and Design, Third Edition Comprehensive63

64 int main() { int *a[3]; int x = 5,y = 10, z = 15,i; a[0] = &x; a[1] = &y; a[2] = &z; for(i=0; i<3; i++) { printf("address = %u\t", a[i]); printf("value = %d\n", *(a[i])); } } Programming Logic and Design, Third Edition Comprehensive64

65 /* Result of execution address = 65518value = 5 address = 65516value = 10 address = 65514value = 15 Programming Logic and Design, Third Edition Comprehensive65

66 66 Passing an Array to a Method Array: list of elements –Single element used in same manner as single variable of the same type Single array element passed by value –Copy of array element passed to method Entire array passed by reference Method receives memory address of the array –Accesses values in array elements Changes to array elements within method are permanent

67 Passing single array element void displayElement(int mark) { printf(“%d ”,mark); } int main() { int length=4; int subMark[length]={50,58,50,60}; for(i=0;i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/12/3491282/slides/slide_67.jpg", "name": "Passing single array element void displayElement(int mark) { printf( %d ,mark); } int main() { int length=4; int subMark[length]={50,58,50,60}; for(i=0;i

68 Passing single Entire array void displayElement(int mark[],int length) { int i; for(i=0;i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/12/3491282/slides/slide_68.jpg", "name": "Passing single Entire array void displayElement(int mark[],int length) { int i; for(i=0;i

69 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 Array69

70 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 70

71 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 Array71

72 Using Parallel Arrays Example: studentId-mark –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 Array72

73 Array73 Figure 6-9 Parallel arrays studId12345 Marks2044332211

74 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 Array74

75 /*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; } Array75

76 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 Array76

77 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”); } Array77

78 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 Array78

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

80 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 Array80

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

82 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 { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/12/3491282/slides/slide_82.jpg", "name": "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

83 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 Max_Month print “Invalid month” get month endwhile month=month-1 print Month_Name[month] stop Array83


Download ppt "Chapter 8: Arrays Programming Logic and Design, Third Edition Comprehensive."

Similar presentations


Ads by Google