1 / 55

CHAPTER 5

CHAPTER 5. ARRAYS. LEARNING OUTCOMES. After studying this chapter, you should be able to: Recognize the array initialization ; Write C programs that use arrays ; Test and debug the input and output from programs that use arrays ; Differentiate one-dimensional and two-dimensional arrays;

mayes
Télécharger la présentation

CHAPTER 5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 5 ARRAYS

  2. LEARNING OUTCOMES After studying this chapter, you should be able to: • Recognize thearray initialization; • Write C programs that use arrays; • Test and debug theinput and output from programs that use arrays; • Differentiate one-dimensional and two-dimensional arrays; • Comprehend the techniqueson passing arrays as function arguments; • Apply thetwo-dimensional arrays in matrices applications; and • Appreciate searching and sorting algorithms.

  3. INTRODUCTION • Imagine you have to write a program that asks the users to repeatedly enter twenty test marks. Our program can be written as: • We actually updated the same test marks for twenty times. The only problem with this program is, later on, we might not be able to view all the marks that have been entered!

  4. ARRAYS • An array is a group of memory locations. • They are referred by: • the same name • the same data type

  5. DECLARATION OF ONE-DIMENSIONAL ARRAY • One-dimensional array is also called a single-dimensional array. • A list of items of the same data type that is declared using a single group name. • The general form of declaration is: type array_name[size]; • The declaration statement has: • type-type of items that will be contained in the array (int, float, double or char). • array name • size-the maximum number of items that can be stored.

  6. DECLARATION OF ONE-DIMENSIONAL ARRAY float finalResults[10]; • Instructs the compiler to declare an array of 10 memory locations with the name finalResults

  7. DECLARATION OF ONE-DIMENSIONAL ARRAY • A good programming practice is to define the array size as a symbolic constant before declaring the array. • For example: #define SIZE 25 float finalResults[SIZE];

  8. EXERCISE 5.1

  9. INITIALIZATION OF ONE-DIMENSIONAL ARRAY • We can initialize an array during the declaration. • The general form of an array initialization is: type array_name[size] = {list of values}; • The values in the array (also known as initializers) can be separated by commas. For example the statement: int numbers[3] = {0,0,0};

  10. INITIALIZATION OF ONE-DIMENSIONAL ARRAY • An array size may be omitted. • The compiler will allocate enough space for all initialized items. • For example: int counter[] = {1,1,1,1};

  11. EXERCISE 5.2

  12. ACCESSING ARRAY ITEMS • Each element in the array is called an array item. • The array items are stored sequentially, with the first array item stored in the first reserved memory location, the second item stored in the second reserved location, and so on until the last item is stored in the last reserved location.

  13. ACCESSING ARRAY ITEMS • Each item can be accessed by specifying the array name and its individual position in sequence. • This position is called subscripted or indexed value. For one-dimensional array, the first item always has the index of 0, the second item has index of 1, and so on. • For example: nums[0]; //refers to first item in array nums; nums[1]; //refers to second item in array nums; nums[2] ; //refers to third item in array nums; nums[3] ; //refers to fourth and last item in array nums;

  14. ACCESSING ARRAY ITEMS

  15. EXERCISE 5.3

  16. PROCCESSING ARRAY ITEMS • We can process the array items in sequence, starting from item zero, ending with last item. • We can accomplish this by using repetition structure like while, for, or do-while loop. • An example of reading data into array then displaying its items.

  17. PROCCESSING ARRAY ITEMS

  18. EXERCISE 5.4

  19. FINDING THE TOTAL AND AVERAGE OF ARRAY ITEMS • Suppose we want to read an array of n floating-point numbers and then calculate their total and average. • Formula for calculating total is: total = X1 + X2+ .. + Xn // where n represents array size • Formula for calculating average is: average = total / n

  20. FINDING THE TOTAL AND AVERAGE OF ARRAY ITEMS

  21. EXERCISE 5.5

  22. ARRAYS AS FUNCTION ARGUMENTS • Individual array items are passed by value to a function: isPositive(myFloats[0]); • An entire array can be passed to a function as an argument: total = calculate(myFloats); • Note that the function prototype could have been written with or without argument name as: float calculate(float []); or float calculate(float myFloats[]);

  23. Example 5.5 illustrates a C program that uses a one-dimensional array to store 5 temperatures entered by user in an array named Fahrenheit

  24. EXERCISE 5.6

  25. SEARCHING AND SORTING ALGORITHMS • Imagine you are working as a data entry clerk at the Admissions and Records Department of a local university. Among your daily tasks is to update students profile data. • How do you feel if the students lists you are looking at are not sorted in any kind of sort order? • How long will you take to find/search for a particular student record if student’s records are not sorted in alphabetical order?

  26. SEARCHING ALGORITHMS • Searching algorithm is an algorithm for finding or locating an item with specific value from an array. • Two searching algorithms will be discussed: • Sequential • Most common search algorithm • Advantage: the algorithm is simple, and the array items no need to be sorted • Binary • Faster than sequential search • But works on sorted array only.

  27. SEQUENTIAL SEARCH • Requires an array to hold a list of items, and one variable that holds the corresponding data to be searched (search key value). • Compares the search key value to each item in the array until a match is found, or until the end of the array has been encountered.

  28. SEQUENTIAL SEARCH • Once the user entered the search key value, the search begins. • Sequential search algorithm works as follows: • For each item in the array, • Check to see if the item you are looking for matches the item in the array. • If it matches, return the index where you found it.

  29. SEQUENTIAL SEARCH • If it does not match, continue searching until you reach the end of the array. • If we get here, we know the item does not exist in the array.

  30. BINARY SEARCH • Works only on sorted arrays. • Compares the search key with value in the middle. • Then divide an array into two half and work with half of the array each time until a match is found. • Much faster than sequential search.

  31. BINARY SEARCH

  32. SORTING ALGORITHMS • One of the most common applications in computer science is sorting. • Sorting is the process through which data array items are arranged according to their values (ascending or descending order). • The most popular sorting algorithms: • Selection Sort • Bubble Sort.

  33. THE SWAPPING TECHNIQUE • Consider array num [] was initialized as follows: int num[5] = {7, 4, 1, 9, 5}; • When we try to swap num[0] and num[1], technically we want 7 to replace 4 and 4 to replace 7. • This means that, we are trying to exchange location for these two array items.

  34. THE SWAPPING TECHNIQUE • Observe the following algorithm. Why this algorithm would seem to be invalid? num[0] = num[1]; // Step 1 num[1] = num[0]; // Step 2 • As a result of this invalid swapping, both num[0] and num[1] will contain 4. • To perform a valid swapping, you need to use a temporary variable to hold the content of num[0].

  35. THE SWAPPING TECHNIQUE • The following three steps code will perform the valid swapping: temp = num[0]; // Step 1 num[0] = num[1]; // Step 2 num[1] = temp; // Step 3 • Figure 5.9 shows how the process will look like in memory, as a temporary variable is introduced in the algorithm.

  36. SELECTION SORT • One of the simplest sorting algorithms. • It finds the smallest items in the array and puts it in the very first position. • Then it finds the next smallest item and places it on the second position, and so on until the array is sorted in ascending order. • To place an item into its position, it swaps positions with the item in that location.

  37. SELECTION SORT • Find the minimum value in the array. • Swap it with the value in the first position. • Repeat the steps above for remainder of the array (starting at the second position).

  38. BUBBLE SORT • The array items are sorted by comparing each adjacent pair of items in turn, swapping the items if necessary, and repeating the pass through the array until no swaps are done. • Bubble sort uses n passes (where n is the number of items). • The word “bubble” means movement of smallest array item value to top of array. • For each pass, an item is compared with the next item down the array and swapped if not in correct order.

  39. BUBBLE SORT • The array status after first pass.  • The highest item value is sorted at last position. • Next pass will sort the next highest item value in the next last position. • This loop will repeat itself until all items are sorted in increasing order.

  40. EXERCISE 5.7

  41. TWO-DIMENSIONAL ARRAYS • Two-dimensional arrays are used to store information that we want to represent in Table or Matrix form. • Similar to one-dimensional array, all of the items data types in a two-dimensional must be of the same type.

  42. DECLARATION OF TWO-DIMENSIONAL ARRAYS • The following declaration creates a two-dimensional array called nums2D[][], which contains 5 rows and 4 columns. #define ROWS 5 #define COLS 4 int nums2D [ROWS][COLS];

  43. INITIALIZATION OF TWO-DIMENSIONAL ARRAYS • A two-dimensional array may be initialized as follow:

  44. TWO DIMENSIONAL ARRAY APPLICATION IN MATRICES • Matrices are numbers tabulated in table with predetermined number of rows and columns. • The three matrices are having the same number of columns and rows, which are 2 by 3 matrices. • We also know that: Matrix_C[0][0] = Matrix_A[0][0] + Matrix_B[0][0] • Hence, the following formula can be applied to a Matrix Addition program: Matrix_C[i][j] = Matrix_A[i][j] + Matrix_B[i][j];

More Related