Presentation is loading. Please wait.

Presentation is loading. Please wait.

Understanding Arrays and How They Occupy Computer Memory

Similar presentations


Presentation on theme: "Understanding Arrays and How They Occupy Computer Memory"— Presentation transcript:

1 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

2 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

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

4 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

5 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

6 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

7 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

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

9 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

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

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

12 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

13 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

14 //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

15 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

16 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

17 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

18 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

19 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

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

21 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

22 /. 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

23 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

24 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

25 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

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

27 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

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

29 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

30 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

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

32 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

33 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

34 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

35 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

36 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

37 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

38 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


Download ppt "Understanding Arrays and How They Occupy Computer Memory"

Similar presentations


Ads by Google