1 Lab Session-XII CSIT121 Spring 2002 b Arrays and Their Usage b Finding the largest element b Lab Exercise 12-A b Lab Demo (12-B) b Practice Problems
2 Arrays and Their Usage b Arrays hold similar and related data items however data values are different b We can use arrays in any program where we have to deal with large amount of similar data using an INDEX into the data
3 Finding Largest Value b Often we will need to find the largest value in an array. b We can designate the first element as the largest in the beginning b As we compare one by one, we change mind if a larger value is found
4 Lab Exercise 12-A b Let us define an array and initialize it with some values b const int PLACES=15 b int distances[PLACES]={24,56,78,24, b 12,94,18,91,77,11,97,82,45,95,88}; b We wish to find the largest distance value in this array
5 Lab Exercise 12-A Data Modeling b an array int distances[] b an integer largest as index to largest value Algorithm b largest=0, for (1 to PLACES-1) Repeat 1 & 2 b 1. Designate distances[largest] as largest b 2. Compare with current value and change the largest index if found higher
6 Lab Exercise 12-B (Demo Required) b Develop a program that keeps information of names and ages of a group of 5 people.. An array of structs is recommended. This program calls a function and passes the array to it. The function prints the names and ages of all people in a nicely formatted way. Sample Data that can be used is as follows:
7 Sample Data for Ex 12-B b b Jason Anderson, 21 b b Christina Smith, 35 b b Brian Smith Jr., 42 b b Derek Dustin, 18 b b Jason Geiger, 19
8 Practice Problem b Given an array of ID numbers of library defaulters, search for the occurrence of a specific ID number to see if this person is a library defaulter or not Data Modeling b int defaulters[MAXSIZE]; b int target_ID; b bool not_found;
9 Practice Problem Algorithm b not_found=true; b While (not_found) b Match the target_ID with contents of the defaulters array one by one b If matched, assign not_found=false b Else if array end reached, person not found
10 Sample Data b const int MAXSIZE=20; b int defaulters[MAXSIZE] = b {2435,1211,7643,2437,9834,2001,1029,1290, b 2340,2200,1214,4438,2105,4355,8254,9120, b 2502,9403,1006,1205}; b target_ID = 8254 b target_ID=2000
11 Additional Practice Problems b Define a union that can hold temperature. The temperature can be stored in degrees Celsius or degrees Fahrenheit. Assign 35 degrees Celsius to the appropriate union member and display. Then convert it to Fahrenheit, store and display b Modify 12-B to include a union in the struct. This union should be able to sore the age in months or years
12 For Lab 13, Demo Problem b Write a value returning recursive function that implements the recursive formula: b F(N) = F(N-1) – F(N-2) b Where F(1) equals 9 and F(0) equals 3; b HINT: The base case here could be reached when N-1 equals 1 and N-2 equals zero