CSEB113 Principles of Programming 1:

Download Report

Transcript CSEB113 Principles of Programming 1:

CHAPTER 7: Arrays

CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon

BS (Feb 2012) 1

Topics

1. Introduction to Arrays 2. Operations on Arrays: a) Declaring arrays b) Initializing arrays c) Assigning values to array elements d) Reading values from array elements e) Passing arrays to a function 3. 2 Dimensional (2D) Arrays

BS (Feb 2012) 2

Topic 1 INTRODUCTION TO ARRAYS

BS (Feb 2012) 3

• • • •

What are arrays?

In C, a group of items of the same type can be set up using array.

An array is a group of

consecutive memory locations

related by the fact that they all have the

same name

and the

same type

.

The compiler must reserve storage (space) for each element/item of a declared array.

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

• To refer to a particular location or element in the array, we specify the name of the array (

index

or

subscript

) and the

position number

of the particular element in the array.

BS (Feb 2012) 4

Array: Conceptual View (1)

Starts with zero A subscript can be an integer or an integer expression. For example if x = 1 and y = 2, then score[x+y] is equal to score[3].

// C array declarations // An array of 4 elements with // no value.

int score[4]

Index (subscript)

score[0] ?

score[1] ?

score[2] ?

score[3] ?

Name of the array

BS (Feb 2012) 5

Array: Conceptual View (2)

Index (subscript)

Name of the array // C array declarations // An array of 4 // elements with no value.

int score[4] score[0] score[1] score[2] score[3] ?

?

?

?

BS (Feb 2012) 6

Array: Conceptual View (3)

Index (subscript)

score [0] ?

// C array declarations // An array of 4 elements with no value.

int score[4] [1] ?

[2] ?

[3] ?

Name of the array

BS (Feb 2012) 7

Topic 2 OPERATIONS ON ARRAYS

BS (Feb 2012) 8

1. Declaring Arrays

Array declaration is made by specifying the data type, it’s name and the number of space (size) 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]; int a[27], b[10], c[76]; double bigval[5*200]; Constant #define SIZE 20 double test_score[SIZE]; int tax[SIZE+2]; expression

BS (Feb 2012) 9

2. Initializing Arrays (1)

• • After an array is declared, it must be initialized.

2 ways to initialize an array: compile-time and run-time 1. Compile-time, example: • int age[ ] = {1, 2, 3, 4, 5}; Initialize as many elements as we want. The array size is not specified.

• int age[3] = {90, 21, 22}; age[0] age[1] age[2] 91 21 22 age[0] age[1] age[2] age[3] age[4] 1 2 3 4 5

BS (Feb 2012) 10

2. Initializing Arrays (2)

char init[5] = {‘a’,’d’}; Initialize the first two elements to the value of respectively, while the other elements are initialized to NULL for char or zero for numeric identifier.

a and d [0] [1] [2] [3] [4] init a d NULL NULL NULL int age[5] = {0}; char ans[4] = {0}; age [0] [1] [2] [3] [4] 0 0 0 0 0 Initialize all array elements to zero.

ans [0] [1] [2] [3] NULL NULL NULL NULL

BS (Feb 2012) 11

2. Initializing Arrays (3)

2. Run-time, example: Using for loop to initialize the array elements salary [0] [1] [2] [3] [4] ?

?

?

?

?

double salary[5]; for (i = 0; i < 5; i++) salary[i] = 0.0; // scanf(“%d”, &salary[i] is accepted.

/*end for */

BS (Feb 2012)

salary [0] [1] [2] [3] [4] 0.0

0.0

0.0

0.0

0.0

12

3. Assigning Values to Array Elements

1. You can assign values to array elements by using the

for

statement (use the same example of initializing arrays during run-time) 2. You can also assign a value to a specific array element by using its

index

number.

– Example: let’s say we have an array that represent the number of people staying in 5 unit apartments.

int apartment[5]={3,2,6,4,5};

– The above initialization indicates that there are 3 people living in apartment[0] , 2 people living in apartment[1] and so on.

– To assign new value to apartment[3] , you may use this statement:

apartment[3] = 8; apartment[3] = apartment[3] + 2

BS (Feb 2012) 13

4. Reading Values of Array Elements

• • To read a value from a specific array element, refer to the index.

For example, let’s say we want to know how many people leaving in apartment[3], we could simply do this: int apartment[5] = {3,2,6,4,5}; int nop; nop = apartment[3]; printf(“Apartment 3 has %d people.”, nop); • Output: Apartment[3] has 4 people.

BS (Feb 2012) 14

#include #define SIZE 5

Example (1)

Output?

void main(void) { int apartment[SIZE] = {3,2,6,4,5}; int index, total = 0; for (index = 0; index < SIZE; index++) { total = total + apartment[index]; } } printf("There are total of %d inhabitants",total);

BS (Feb 2012) 15

Example (2)

#include void main(void) { int apartment[5] = {3,2,6,4,5}; int index, total = 0; printf("Apt No\t\tNo of people"); for (index = 0; index < 5; index++) { printf(“%d\t\t%d\n",index, apartment[index]); } }

Output?

BS (Feb 2012) 16

5. Passing Arrays to Functions(2)

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, calling function.

any changes to the array inside the function will also change the actual array inside the • 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?

BS (Feb 2012) 17

5. Passing Arrays to Functions(2)

• • • Assume that we have the following array declaration.

int score[3]={45,90,14}; Say for example we want to write a function, called ReadScore(), which will read marks/scores from the user and store the marks inside the score array.

Perform these steps: – Function prototype - indicate that the parameter is an array. Example: void ReadScore(int s[]); – Function call: int score[3]={45,90,14}; //Assume we have this ReadScore(score); //declaration – Function definition : void ReadScore(int s[]){ with NO array size information.

}

BS (Feb 2012) 18

Example (1)

#include void test(int s[]);

Output?

void main(void) { int x[3]={9,7,6}; test(x); } void test(int s[]) { printf("%d\n",s[0]); printf("%d\n",s[1]); }

BS (Feb 2012) 19

Example(2)

#include #define size 5 void getMarks(float s[ ]); float calcAverage(float sc[ ]); void main(void) { float marks[size] = {0.0}; //initializing the array getMarks(marks); /* function call */ printf("Average for marks given is %.2f\n“, calcAverage(marks)); } void getMarks(float s[ ]) { int i; for (i = 0; i < size; i++) { printf("Marks student %d:",i + 1); scanf("%f",&s[i]); } }

BS (Feb 2012)

float calcAverage(float sc[ ]) { } float total = 0.0; int i; for (i = 0; i < size; i++) { total = total + sc[i]; } return (total / size);

20

Topic 3 2 DIMENSIONAL (2D) ARRAYS

BS (Feb 2012) 21

2D Arrays

• • • It is possible to create an array which has more than one dimension.

In C, we can go up to 12-dimensional arrays.

2D arrays: – Declaration:

Data_type array[row][column]

• Example: int carrymarks[4][2] Row Column

BS (Feb 2012) 22

2D: Conceptual View (1)

Row subscript Column subscript int m[4][2] = {10, 12, 33, 14, 25, 56, 77, 85}; Row [0] [1] [2] [3] [0] 10 33 25 77 This 2D array has 4 rows and 2 columns.

Column [1] 12 14 56 85

BS (Feb 2012) 23

2D: Conceptual View (2)

int m[4][2] = {10, 12, 33, 14, 25, 56, 77, 85}; Row 0 Row 1 Row 2 Row 3 Column 0 m[0][0] 10 m[1][0] 33 m[2][0] 25 m[3][0] 77 Column 1 m[0][1] 12 m[1][1] 14 m[2][1] 56 m[3][1] 85 This 2D array has 4 rows and 2 columns.

Storage structure

m[0][0] m[0][1] m[1][0] m[1][1] m[2][0] m[2][1] m[3][0] m[3][1] 10 12 33 14 25 56 77 85 Row 0 Row 1 Row 2 Row 3

24

Initializing 2D Arrays (1)

2 ways to initialize an array: compile-time and run-time

1. Compile-time

– Variable initialization can also be done this way: int m[4][2] = {{10,12},{33,14},{25,56},{77,85}}; – This method is less confusing since we can see the rows and columns division more clearly.

BS (Feb 2012) 25

Initializing 2D Arrays (2)

2. Run-time

Using nested for statements: for (row = 0; row < 4; row++) { for (column = 0; column < 2; column++) m[row][column] = 0; } • Although it is possible to create a multi-dimensional array, arrays above 2-dimensions are rarely used.

BS (Feb 2012) 26

• •

Passing a 2D Array to Functions

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 m[4][5]; Then the function header which would take as an argument should be declared like this: void Process2D(int td[ ][5]) m 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.

BS (Feb 2012) 27

Summary

1. Introduction to Arrays 2. Operations on Arrays: a) Declaring arrays b) Initializing arrays c) Assigning values to array elements d) Reading values from array elements e) Passing arrays to a function 3. 2 Dimensional (2D) Arrays – declaring, initializing and passing 2D array to function

BS (Feb 2012) 28