Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Procedural Programming Session Five: Arrays Name: First Name: Tutor: Matriculation-Number: Group-Number: Date: Prof. Dr.Ing. Axel Hunger Dipl.-Ing. Joachim Zumbrägel Universität Duisburg-Essen Faculty of Engineering, Department Electrical Engineering and Information Technology Computer Engineering Procedural Programming/Lab5 1
Introduction Sometimes it s rather useful to store same type of data together. In programming, this is done using an array. Arrays are a collection of variables having the same data type, placed contiguously in memory. Declaring an Array Like the other variables, an array needs to be defined. The computer needs to know what kind of an array we need, and how large it should be. We can declare an array as array_type array_name [array_size ]; For example: int temp[7]; Here int specifies the data type of the array variable, just like when used with simple variables, and the word temp is the name of the array. The subscript [7], tells how many variables of the type int will be in array. Any one of these elements may be referred to by giving the array name followed by the position number of the particular element in the square brackets [ ]. First element in an array is always the zero th element. So the first element of the array temp is referred to as temp[0], the second as temp[1 ] and so on. The following figure shows a graphical illustration of what the array looks like: 0 1 2 3 4 5 6 temp Initializing Array Elements To initialize an array we can use the array name along with its reference, followed by an equal sign. For example: temp[0] = 10; temp[1] = 20; An array can also be initialized along with the array declaration by following the declaration with an equal sign and a comma separated list enclosed in the braces of initializers. For example: int temp[7] = 10, 20, 30, 40, 50, 60, 70; Procedural Programming/Lab5 2
The initialization of an array must not be necessarily complete. What means it is allowed to initialize just some of the array elements. For example: int temp[7] = 10, 20, 30; The example above initializes only the first three elements (temp[0], temp[1],temp[2]. All other elements t(emp[3] temp[6]) will be initialized with 0. Hint: If you don t initialize an array which has a local scope (what means it is defined within a function) the elements of the array have random values. When you define an array with a global scope all elements will initialized with 0. Accessing Array Elements by Subscript We can refer to an array's element by its number. This allows us to use a variable, usually called a subscript, to reference the elements in the array. For example: double temp[7] = 10, 20, 30, 40, 50, 60, 70; int i; So now, if we execute i = 3; then temp[i] refers to the element temp[3], which has the value 40. If we now execute i = 1; then temp[i] refers to the element temp[1], which has the value 20. Exercise 5.1: Declare an array studentpercentage of type integer that will store the percentages of students in a class of 25. Exercise 5.2: Assign the value 76.5 to array element nine. Procedural Programming/Lab5 3
Exercise 5.3: Name the fourth element of the array. Exercise 5.4: Refer to the array element 10. Exercise 5.5: Print array elements 3 and 5 with two digits of precision to the right. Exercise 5.6: Assign the value 80.50 to the seventh element of the array. Exercise 5.7: In the following declaration, what values would each array element be initialized to: int array[5] = 1,2,3; Procedural Programming/Lab5 4
Example: The following program computes and prints the total and average of five numbers using arrays: /* example: arrays */ #include <stdio.h> int main() float nums[5]; float total; float average; nums[0] = 30; nums[1] = 25; nums[2] = 42; nums[3] = 86; nums[4] = 23; total = nums[0] + nums[1] + nums[2] + nums[3] + nums[4]; average = total / 5; printf("total = %2.f, Average = %2.f \n", total, average); return 0; Procedural Programming/Lab5 5
Processing an Array In order to process an array, the for loop is an ideal control structure to use with it. The subscript of the array will act as the counter of the for loop. With each iteration, of the loop, the loop body will process the array element which is specified by the subscript. Suppose that you just finished taking classes at a local university and want to average your six class scores. The following program initializes one array for the school name and another for the six classes. The body of the program averages each of the six scores. Example: /* example: Average of five test marks */ #include <stdio.h> int main() char sname[] = University of Duisburg-Essen ; float marks[5] = 88.7, 90.4, 76.0, 100.0, 86.7; float average = 0.0; int ctr; /* Calculating total of the marks */ for (ctr = 0; ctr < 5; ctr++) average += marks[ctr]; /* Calculating the average */ average /= (float)5; printf("at %s, your class average is %.1f.", sname, average); return 0; Procedural Programming/Lab5 6
Exercise 5.8: Print all the elements of the array marks[], one by one, from Exercise 5.1, using a for loop within a function. Exercise 5.9: Write a loop which initializes 10 elements of an integer array counts to zeros. Procedural Programming/Lab5 7
Searching an Array Arrays are one of the main ways through which data is stored in C programs. There can be many places where they are used, ranging from employee payroll program to customer account processing in a bank. Data is usually read into an array from the keyboard or from files. File processing is described in a later session. For now, you should just know how to process the arrays. To search an array, you don t need to know any special types of new command or functions. The if statement and the for loop is basically all you need. To search for a particular value in an array, you need to compare each element in that array using the if statement to check whether they match or not. if they don t, you have to keep searching till they match or till you run out the array elements. Example: /* exercise: Searching the highest value in the array */ #include <stdio.h> #define SIZE 15 int main() // Store some values in the array */ int array[size] = 5,2,7,8,36,4,2,86,11,43,22,12,45,6,85; int highestval, ctr; highestval = array[0]; //Initializes with first array element for (ctr = 1; ctr < SIZE; ctr++) // Stores current value if it is higher than the highest so far if (array[ctr] > highestval) highestval = array[ctr]; printf("the highest number in the list is %d.", highestval); return 0; Procedural Programming/Lab5 8
Explanation: In the given example, to find the highest number in an array, the program compares each element with the first one. If it finds a higher value, it becomes the basis for the rest of the array. This continues till the end of the array is reached and you have the highest value. The #define keyword is a preprocessing directive. So for example, in the above code: #define SIZE 15 int array[size] actually gets swapped for int array[15] when the compiler comes across it. Sorting Arrays Sorting can be defined as the process of placing data in order whether alphabetically or numerically. It is one of the most common and important tasks in computer applications. Practically every organization sorts their data in one way or another. For example, a phone company may sort their phone directories by customer last name in order to make it easy when searching for phone numbers. There are virtually hundreds of different ways to sort an array, but the main goal of these methods is to compare each element of an array to another element and swap them if they are in a wrong order. The bubble sort is one of the easiest of the most commonly used algorithms for sorting arrays; therefore we will use this as an example. Example: /* Using Bubble Sort as a Function */ #include <stdio.h> void bubble_sort(int [], int); int main() int array[100], n, c, d; printf("how many elements do you want to enter?\n"); scanf("%d", &n); printf("enter %d the elements:\n", n); for (c = 0; c < n; c++) Procedural Programming/Lab5 9
scanf("%d", &array[c]); bubble_sort(array, n); printf("sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0; void bubble_sort(int list[], int num) int x, y, temp; //Bubble sort function for(x = 0; x < num; x++) for(y = 0; y < num-x-1; y++) if(list[y] > list[y+1]) temp = list[y]; list[y] = list[y+1]; list[y+1] = temp; Explanation: This algorithm basically works by repetitively going through the list, comparing each pair of adjacent values and swapping them if they are in the incorrect position. The algorithm keeps on repeating till no more swapping is needed, which indicates that the list is sorted. This is done by using a third temporary variable to temporary hold values of those two variables which we want to swap with each other. Procedural Programming/Lab5 10
Multidimensional Arrays It is also possible for arrays to have two or more dimensions. This allows them to imitate multidimensional objects such as tables with rows and columns. Declaring Multidimensional Arrays In order to declare a two dimensional array, specify the array data type and the size of the array and then place the number of rows and the number of columns each in its own square bracket. For example: int student_grade[7][10]; The above statement declares a two dimensional array of integers of size 7 rows x 10 columns. Exercise 5.10: Define a 2 x 5 integer array named as students. Exercise 5.11: Declare a two dimensional array that will hold temperatures for each hour of the day for a whole year. Procedural Programming/Lab5 11
Example: The following program stores temperature for each day of the week for a whole month in a two dimensional array of size 4 x 7: /* example: multidimensional_arrays */ #include <stdio.h> int main() int monthtemps[4][7]; printf("enter the temp for week 1 day 1: "); scanf("%d", &monthtemps[0][0]); printf("enter the temp for week 1 day 2: "); scanf("%d", &monthtemps[0][1]); printf("enter the temp for week 1 day 3: "); scanf("%d", &monthtemps[0][2]); printf("enter the temp for week 1 day 4: "); scanf("%d", &monthtemps[0][3]); printf("enter the temp for week 1 day 5: "); scanf("%d", &monthtemps[0][4]); printf("enter the temp for week 1 day 6: "); scanf("%d", &monthtemps[0][5]); printf("enter the temp for week 1 day 7: "); scanf("%d", &monthtemps[0][6]); printf("enter the temp for week 2 day 1: "); scanf("%d", &monthtemps[1][0]); printf("enter the temp for week 2 day 2: "); scanf("%d", &monthtemps[1][1]); printf("enter the temp for week 2 day 3: "); scanf("%d", &monthtemps[1][2]); printf("enter the temp for week 2 day 4: "); scanf("%d", &monthtemps[1][3]); printf("enter the temp for week 2 day 5: "); scanf("%d", &monthtemps[1][4]); printf("enter the temp for week 2 day 6: "); scanf("%d", &monthtemps[1][5]); printf("enter the temp for week 2 day 7: "); Procedural Programming/Lab5 12
scanf("%d", &monthtemps[1][6]); printf("enter the temp for week 3 day 1: "); scanf("%d", &monthtemps[2][0]); printf("enter the temp for week 3 day 2: "); scanf("%d", &monthtemps[2][1]); printf("enter the temp for week 3 day 3: "); scanf("%d", &monthtemps[2][2]); printf("enter the temp for week 3 day 4: "); scanf("%d", &monthtemps[2][3]); printf("enter the temp for week 3 day 5:"); scanf("%d", &monthtemps[2][4]); printf("enter the temp for week 3 day 6:"); scanf("%d", &monthtemps[2][5]); printf("enter the temp for week 3 day 7:"); scanf("%d", &monthtemps[2][6]); printf("enter the temp for week 4 day 1: "); scanf("%d", &monthtemps[3][0]); printf("enter the temp for week 4 day 2: "); scanf("%d", &monthtemps[3][1]); printf("enter the temp for week 4 day 3: "); scanf("%d", &monthtemps[3][2]); printf("enter the temp for week 4 day 4: "); scanf("%d", &monthtemps[3][3]); printf("enter the temp for week 4 day 5: "); scanf("%d", &monthtemps[3][4]); printf("enter the temp for week 4 day 6: "); scanf("%d", &monthtemps[3][5]); printf("enter the temp for week 4 day 7: "); scanf("%d", &monthtemps[3][6]); return 0; Procedural Programming/Lab5 13
Exercise 5.12: Declare a two dimensional array that contains 15 rows, each of which will store 12 integers. Exercise 5.13: State whether there is any difference between the following two array declarations: a) int arr1[2][3] = 1, 2, 3,4, 5, 6; b) int arr2[2][3] = 1, 2, 3, 4, 5, 6; Procedural Programming/Lab5 14