prepared by mmd, edited by msy1 chapter 4 array. prepared by mmd, edited by msy2 arrays ...

33
Prepared by MMD, Edited by MSY 1 CHAPTER 4 ARRAY

Upload: cora-bradley

Post on 17-Jan-2018

227 views

Category:

Documents


0 download

DESCRIPTION

Prepared by MMD, Edited by MSY3 Introduction to Arrays  Built-in C data types: Fundamental data types – char, int, double, float, void and variations of int and double. When a variable is declared as one of these types, the compiler reserves a memory location for the variable and it can only store only one value at a time. Derived data types – derived from fundamental data types eg. pointers, arrays, structures and unions.  An array is a group of memory locations related by the fact that they all have the same name and the same type.

TRANSCRIPT

Page 1: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 1

CHAPTER 4ARRAY

Page 2: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 2

Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function Simple sorting: bubble sort Simple searching: linear sort 2-dimensional array

Page 3: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 3

Introduction to Arrays Built-in C data types:

Fundamental data types – char, int, double, float, void and variations of int and double. When a variable is declared as one of these types, the compiler reserves a memory location for the variable and it can only store only one value at a time.

Derived data types – derived from fundamental data types eg. pointers, arrays, structures and unions.

An array is a group of memory locations related by the fact that they all have the same name and the same type.

Page 4: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 4

Introduction to Arrays Cont… To refer to a particular location or element in the

array, we specify the name of the array and the position number of the particular element in the array.

The size of an array is static (fixed) throughout program execution.

Page 5: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 5

Let say we have an array called A

Name of the array

The position number withinthe square brackets is formallycalled a subscript. A subscriptcan be an integer or an integerexpression. For example if x = 1 and y = 2, then A [x+y]is A [3].

Notice that the positionstarts from 0.

Position/index number of theelement within the array

-1099-810027

1976-2020

1

A[0]A[1]A[2]A[3]A[4]A[5]A[6]A[7]A[8]

1

Page 6: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 6

Declaring Arrays Array declaration is made by specifying the

data type and the number of space so that the computer may reserve the appropriate amount of memory.

General syntax:data_type array_name[size]

Examples: int my_array[100]; char name[20]; double bigval[5*200]; int a[27], b[10], c[76];

Page 7: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 7

Initializing Arrays There are 2 ways to initialize an array:

during compilation and during execution.1. During compilation:

Unsized array e.g int arr[] = {1, 2, 3, 4, 5}; We can define how many elements that we want

since the array size is not given. Sized array e.g int arr[3] = {90, 21, 22};

We can define only 3 elements since the array size is already given.

2. During execution:int arr[3], j;for (j = 0; j < 3; j++) arr[j] = 0;

Page 8: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 8

Examples Using Arrays

In the example above, an array with the name temp and size 5 has been declared. The elements in the array has been given the value position*9. The first for loop is equivalent to this:temp[0] = 0*9 temp[3] = 3*9temp[1] = 1*9 temp[4] = 4*9temp[2] = 2*9

#include <stdio.h>#define SIZE 5

void main(void) { int temp[SIZE], i; for (i = 0; i < SIZE; i++) temp[i] = i*9; printf(“%s %13s\n”, “Element”, “Value”); for (i = 0; i < SIZE; i++) printf(“%7d%13d\n”, i, temp[i]);}

Output:

Element Value0 01 92 183 274 36

Page 9: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 9

#include <stdio.h>#define SIZE 10

void main(void) { int list[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int i, total = 0;

for (i=0; i < SIZE; i++) { total += list[i]; } printf(“Total of array element values is %d.\n”, total);}

Output: Total of array element values is 45.

Example:

Page 10: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 10

#include <stdio.h>#define SIZE 20

void main(void) { int list[SIZE]; int n, i, total = 0;

float avg;//user enter how many values to key in and validate itprintf(“enter the size of the data: ”);scanf(“%d”, &n);

if(n<20){ for (i=0; i < n; i++) {

//read values and store in arrayprintf(“enter value %d :”, i);scanf(“%d”, &list[i]);

total += list[i]; } //find average avg=total/n; printf(“Total of array element values is %d.\n”, total); printf(“Average= %.2f\n”, avg); } else printf(“the size of the data is exceeding the array size”); }

Example:

Output: Total of array element values is 45.

Page 11: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 11

Relationship with Pointers The name of an array is actually a pointer

to the first element in the array. Therefore, if we have:

int test[3] = {9, 10, 11}; printf(“%d”, *test); The output would be: 9 There are a few ways to traverse an array:

int test[3] = {9, 10, 11}, k;for (k = 0; k < 3; k++) printf(“%d\n”, test[k]);

int test[3] = {9, 10, 11}, k;int *ptr = test;for (k = 0; k < 3; k++, ptr++) printf(“%d\n”, *ptr);

Page 12: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 12

Array Passing to a Function

A function that is going to receive an array as one of the arguments can be declared in 2 ways:void Process(char name[]) ORvoid Process(char *name)

When we pass an array to a function, we are actually passing the pointer to the first element in the array to the function. Therefore, any changes to the array inside the function will also change the actual array.

Either the array is passed using [] or using *, the array can be accessed in the same way.

Page 13: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 13

Assume that we have the following array declaration.int marks[10] = {0};

Say for example we want to write a function, called get_marks, which will read marks from the user and store the marks inside the array.

When we want to pass an array to a function, we need to know these 3 things. How to write the function prototype? How to do function call? How does the function header would look like?

Passing Array to a Function Cont…

Page 14: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 14

Passing Array to a Function Cont… Function prototype:

/* data type with square bracket */void get_marks(int [ ]); void get_marks(int *); /*treating array as

pointer */ Function call:

get_marks(marks); /* just pass the array name */

Function header:void get_marks(int marks[ ]) void get_marks(int *marks) /*treating array

as pointers */

Page 15: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 15

Example 1: parameter received as an array#include <stdio.h>#define size 10void get_marks(int [ ]);int calc_average(int [ ]);

void main(void){

int marks[size] = {0}; /*initializing the array */get_marks(marks); /* function call */printf(“Average for marks given is %d”, calc_average(marks));

}

Page 16: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 16

Example 1: parameter received as an arrayvoid get_marks(int marks[ ]){

int i;for (i = 0; i < size; i++){printf("Marks student %d:",i + 1);scanf("%d",&marks[i]);}

} int calc_average(int marks[ ]){

int total = 0, i;for (i = 0; i < size; i++){

total = total + marks[i];}return total / size;

}

Page 17: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 17

Example 2: parameter received as pointers A function could also receive/treat array

parameter as pointer. #include <stdio.h>#define size 10

void get_marks(int *);int calculate_average(int *);

void main(void){

int marks[size] = {0};

get_marks(marks);printf("Average for marks given is %d\n", calculate_average(marks));

}

Observe the function prototypes

Page 18: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 18

Example 2: parameter received as pointersvoid get_marks(int *marks){

int i;for (i = 0; i < size; i++, marks++){

printf("Marks student %d: ", i + 1);

scanf("%d", marks);}

}int calculate_average(int *marks){

int i, total = 0;for (i = 0; i < size; i++, marks++){

total = total + *marks;}

return (total / size);}

Manipulating the memory address

Pointer variable

Page 19: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 19

#include <stdio.h>#define SIZE 10

void Read(int []);int CountAvg(int *);

void main(void) { int grades[SIZE]; Read(grades); printf(“The average of the grades given is %d\n”, CountAvg(grades));}

void Read(int grades[]) { int i, temp; for (i=0 ; i<SIZE; i++) { printf(“Enter grade %d\n”, i); scanf(“%d”, &temp) grades[i] = temp; }}

int CountAvg(int *grades) { int i, total=0; for (i=0; i<SIZE; i++) total += grades[i]; return (total/SIZE);}

Example 3:

Page 20: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 20

The Read() and CountAvg() functions can also be written this way:

void Read(int grades[]) { int i; int *ptr = grades; for (i = 0; i < SIZE; i++, ptr++) { printf(“Enter grade %d\n”, i); scanf(“%d”, &(*ptr))

}}int CountAvg(int *grades) { int i, total; int *ptr = grades; for (i = 0, total = 0; i < SIZE; i++, ptr++) total += *ptr; return (total/SIZE);}

Page 21: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 21

Sorting Sorting is the process of placing data into a

particular order such as ascending or descending.

There are many sorting algorithms that are usually used. Among them are bubble sort, selection sort, insertion sort and shell sort.

Here, we will discuss how bubble sort can be used to sort the elements in an array.

Page 22: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 22

Bubble Sort In bubble sort, the list is divided into two

sublists: sorted and unsorted. The smallest element is bubbled from unsorted

sublist and moved to the sorted sublist. Each time an element moves from the

unsorted sublist to the sorted sublist, one sort is completed.

The bubble concept is shown in figure below :

1 j nkSorted Unsorted

Page 23: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 23

Figure below shows how the wall moves one element in each pass.

Looking at the first pass, start with 56 and compare it to 32. Since 56 > 32, it is not moved and we step down one element.

No changes take place until we compare 45 to 8. Since 8 < 45, the two elements are exchanged (swapped).

Bubble Sort cont…

23 78 845 32 56

Unsorted

Original list

Page 24: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 24

Bubble Sort cont… The two elements are swapped and we

step down 1 element. Because 8 was moved down, it is now

compared to 78 and these two elements are swapped.

Finally, 8 is compared to 23 and exchanged. This series of exchanges places 8 in the first location and the wall is moved up one position.23 788 45 32 56

Unsorted

After pass 1

Page 25: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 25

Bubble Sort cont…23 328 78 45 56

Unsorted

After pass 2

23 328 45 78 56

Unsorted

After pass 3

Sorted

23 788 4532 56 After pass 4Sorted!

Sorted

Page 26: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 26

Let us look at the C code:void main(void) {

int list[] = {23, 78, 45, 8, 32, 56}; BubbleSort(list);}

void BubbleSort (int list[]) { int i, j, temp, swapped = 1; for (i = 0; i < 6 && swapped == 1; i++) { swapped = 0; for (j = 0; j < (6-i); j++) { if (list[j] > list[j+1]) { // Swap temp = list[j]; list[j] = list[j+1]; list[j+1] = temp; swapped = 1; } } }}

Page 27: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 27

Simple Searching Searching is the process of determining

whether an array contains a value that matches a certain key value.

Same as in sort, there are more than one algorithms that can be used to do a search.

Here, we will discuss how can we do a linear search on an array.

Linear search is a simple searching algorithm where: data are stored in an array a key value is compared with each elements in the

array starting from the first element

Page 28: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 28

void main(void) { int list[] = {34, 53, 21, 23, 4}; int i, key_value, found = 0; printf(“Enter the number that you want to find: ”); scanf(“%d”, &key_value); for (i = 0; i < 5; i++) { if (list[i] == key_value) { found = 1; printf(“The number %d is found at location %d\n”, key_value, i); break; } }

if (found == 0) printf(“The number %d cannot be found in the list\n”, key_value);}

Let us look at the C code: Sample Output:

Enter the number that you want to find: 53

The number 53 is found at location 1Press any key to continue

Page 29: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 29

2-Dimensional Array It is possible to create an array which has

more than one dimension. For example:

2D array: int array[4][2]; 3D array: int array[4][2][10];

Graphical representation of a 2D array:int myarray[4][2] = {1, 2, 3, 4, 5, 6, 7, 8};

1 23 45 67 8

This array has 4 rows and 2 columns.

Page 30: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 30

Variable initialization can also be done this way: int myarray[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};

int test_score[4][3]={{95,80,78},{69, 75,81}, {100,98,100}, {98,85,87}}; This method is less confusing since we can see the rows

and columns division more clearly. To initialize a 2D array during execution, we need to use

a double loop (nested loop):for (i = 0; i < 4; i++)

for (j = 0; j < 2; j++)total=total + myarray[i][j];

Although it is possible to create a multi-dimensional

array, arrays above 2-dimensions are rarely used.

2-Dimensional Array Cont…

Page 31: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 31

When a 2D (or higher dimensional) array is passed to a function, the size of the second (or subsequent) subscript needs to be specified.

For example, if we have:int twoD[4][5];Then a function which would take twoD as an argument should be declared like this:void Process2D(int td[][5])

An array is stored consecutively in memory regardless of the number of dimensions. Therefore, specifying the subscripts in the function parameter will help the compiler to know the boundary of the different dimensions.

Passing 2D Array to Function

Page 32: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 32

Example

Sample program 1Sample program 2

Page 33: Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays

Prepared by MMD, Edited by MSY 33

SUMMARY In this chapter, we have looked at:

Array declaration and initialization Reading and writing from/to array elements Passing array to function Array sorting : BubbleSort Simple searching : Linear Search 2 dimensional array