chapter 7: arrays (numeric arrays)

29
CHAPTER 7: Arrays (Numeric Arrays) CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1 BS (May 2012)

Upload: ronli

Post on 24-Jan-2016

127 views

Category:

Documents


3 download

DESCRIPTION

CHAPTER 7: Arrays (Numeric Arrays). CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon. Topics. Introduction to one-dimensional (1-D) numeric arrays Operations on arrays: Declaring arrays Initializing arrays Assigning values to array elements - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CHAPTER 7: Arrays (Numeric Arrays)

CHAPTER 7: Arrays (Numeric Arrays)

CSEB113 PRINCIPLES of PROGRAMMING CSEB134

PROGRAMMING I

byBadariah Solemon

1BS (May 2012)

Page 2: CHAPTER 7: Arrays (Numeric Arrays)

Topics1. Introduction to one-dimensional (1-D) numeric

arrays2. Operations on arrays:

– Declaring arrays– Initializing arrays– Assigning values to array elements– Reading and displaying values of array elements

3. More about numeric arrays– Passing 1-D arrays to functions– Two-dimensional (2-D) arrays

2BS (May 2012)

Page 3: CHAPTER 7: Arrays (Numeric Arrays)

INTRODUCTION TO ARRAYS

Topic 1

BS (May 2012) 3

Page 4: CHAPTER 7: Arrays (Numeric Arrays)

What is an Array? (Part 1)• An array is nothing more than a collection of similar data

types such as integers, float and characters.• Programmer often uses a set of identical data that have the

same type and are used for the exact same purpose.• For example, a programmer may wish to keep track of the

training attendance for 5 working days.• Suppose below pattern is observed:

BS (May 2012) 4

Training Day Total Attendance

Monday 48

Tuesday 55

Wednesday 60

Thursday 36

Friday 50

Page 5: CHAPTER 7: Arrays (Numeric Arrays)

What is an Array? (Part 2) • The attendance data serves a common purpose, so it is

natural to group them together in a table.• When stored in a computer memory, it is best to store

this data in adjacent (consecutive) memory cells as follows:

• This kind of arrangement is called an array.• In C, an array has same name and stores data of the

same data type.

BS (May 2012) 5

Mon Tue Wed Thu Fri

48 366055 50

Address 430 432 434 436 438

Page 6: CHAPTER 7: Arrays (Numeric Arrays)

Why Use an Array?• Based on the attendance data, we could easily sum up the

attendance of 5 working days if we use five different variables and an expression as follows:

• However, this solution is not at all elegant and is way too long for such a simple task.

• On the other hand, the use of an array could provides a shorter and elegant solution as we will see next.

BS (May 2012) 6

int mon, tue, wed, thu, fri, sum;

printf(“Enter the daily attendance:”);scanf(%d %d %d %d %d”, &mon, &tue, &wed, &thu, &fri);

sum = mon + tue + wed + thu + fri;

int mon, tue, wed, thu, fri, sum;

printf(“Enter the daily attendance:”);scanf(%d %d %d %d %d”, &mon, &tue, &wed, &thu, &fri);

sum = mon + tue + wed + thu + fri;

Page 7: CHAPTER 7: Arrays (Numeric Arrays)

1-D Array

• An array is identified by its name, type, dimension and number of elements.

• This is an example of a 1-D array declaration:

• Because of this declaration:– The array size is static (fixed) throughout the program execution.– It is a one-dimension (1-D) array (because it has only one pair of [ ]).– The array can be conceptually visualised as:

BS (May 2012) 7

int day[5];

Array name

Array size (maximum no. of elements in the array).

Type of each element of the array

day

Position: [0] [1] [2] [3] [4]or index number

By default begins with zero

Page 8: CHAPTER 7: Arrays (Numeric Arrays)

OPERATIONS ON ARRAYS

Topic 2

BS (May 2012) 8

Page 9: CHAPTER 7: Arrays (Numeric Arrays)

Operations of Arrays• Before you could use an array, you must declare it. Then, you

may want to assign initial values to the array elements.• Once declared you could assign values to the array elements.• Alternatively, you could also declare and assign initial values

to the array elements in one declaration statement.• Once the elements of the arrays have been assigned with

values, you could read and manipulate them (such as by printing them on the screen).

• Working with arrays in C programs is best implemented with looping statements, in particular the for loop.

BS (May 2012) 9

Page 10: CHAPTER 7: Arrays (Numeric Arrays)

Declaring Arrays• Array declaration is made by specifying:

– data type of the array’s elements– array’s name – array’s size

• General syntax:

• Examples: – int myarray[100];– double bigval[5*200];– int a[27], b[10], c[76];

BS (May 2012) 10

data_type array_name[size];

#define SIZE 20double test_score[SIZE];int tax[SIZE+2];

#define SIZE 20double test_score[SIZE];int tax[SIZE+2]; Constant

Declaring multiple arrays of the same data type

Page 11: CHAPTER 7: Arrays (Numeric Arrays)

Initializing Arrays (1)• After an array is declared, it must be initialized.• 2 ways to initialize an array: compile-time and run-

time1. Compile-time, example:

BS (May 2012) 11

Initialize as many elements as we want. The array size is not specified.

90 2221

[0] [1] [2]

age

int num[ ] = {1, 2, 3, 4};int num[ ] = {1, 2, 3, 4};

int age[3] = {90, 21, 22};int age[3] = {90, 21, 22};

1

3

2

[0]

[1]

[2]

num

int day[5] = {0};int day[5] = {0};0 00

[0] [1] [2] [3] [4]

day 0 0

Page 12: CHAPTER 7: Arrays (Numeric Arrays)

Initializing Arrays (2)2. Run-time, example:• Using for loop to initialize the array elements

BS (May 2012) 12

? ?? ??salary

[0] [1] [2] [3] [4]

50 5050 5050salary [0] [1] [2] [3] [4]

int salary[5];

for (i = 0; i < 5; i++)salary[i] = 50;

int salary[5];

for (i = 0; i < 5; i++)salary[i] = 50;

Page 13: CHAPTER 7: Arrays (Numeric Arrays)

Assigning Values to Array Elements

• You can:1. Assign a value to a specific array element by using its

position number or index number. Example:

2. Assign values to several array elements using the looping statement. Example:

BS (May 2012) 13

int day[5];

day[0] = 50;day[3] = day[0] + 2

int day[5];

day[0] = 50;day[3] = day[0] + 2

int day[5], i=0;

while(i<=4){day[i] = 50;i++;

}

int day[5], i=0;

while(i<=4){day[i] = 50;i++;

}

int day[5], i=0;

for(i=0; i<=4;i++)day[i] = 50;

int day[5], i=0;

for(i=0; i<=4;i++)day[i] = 50;

50

[0] [1] [2] [3] [4]

day 52

Page 14: CHAPTER 7: Arrays (Numeric Arrays)

Reading and Displaying Values

• To read and display value from an array element, refer to the position number (or index).

• For example:

• Output:

BS (May 2012) 14

int house[4] = {3,2,6,4};int nop;

nop = house[2];printf(“House 3 has %d people.”, nop);printf(“House 1 has %d people.”, house[0]);

int house[4] = {3,2,6,4};int nop;

nop = house[2];printf(“House 3 has %d people.”, nop);printf(“House 1 has %d people.”, house[0]);

House 3 has 6 people.House 1 has 3 people.

3 62

[0] [1] [2] [3]

house 4

Page 15: CHAPTER 7: Arrays (Numeric Arrays)

Example

BS (May 2012) 15

#include <stdio.h>#define SIZE 4

void main(void){

int house[SIZE] = {3,2,6,4};int index, total = 0;

for (index = 0; index < SIZE; index++){

printf(“House %d: %d”, index+1, house[index]);total = total + house[index];

}

printf("The total: %d", total);}

#include <stdio.h>#define SIZE 4

void main(void){

int house[SIZE] = {3,2,6,4};int index, total = 0;

for (index = 0; index < SIZE; index++){

printf(“House %d: %d”, index+1, house[index]);total = total + house[index];

}

printf("The total: %d", total);}

3 62

[0] [1] [2] [3]

house 4

House 1: 3House 2: 2House 3: 6House 4: 4The total: 15

Page 16: CHAPTER 7: Arrays (Numeric Arrays)

More Example#include <stdio.h>void main(void){ int rain[5], i, sum=0;

for (i=0; i<=4; i++){

printf(“Enter daily rain:”); scanf(“%d”, &rain[i]);

}

for (i=0; i<=4; i++){

printf(“Daily rain: %d”, rain[i]); sum = sum + rain[i];

} printf(“Total rain: %d”, sum);}

#include <stdio.h>void main(void){ int rain[5], i, sum=0;

for (i=0; i<=4; i++){

printf(“Enter daily rain:”); scanf(“%d”, &rain[i]);

}

for (i=0; i<=4; i++){

printf(“Daily rain: %d”, rain[i]); sum = sum + rain[i];

} printf(“Total rain: %d”, sum);}

BS (May 2012) 16

Page 17: CHAPTER 7: Arrays (Numeric Arrays)

Exercise1. Write a program to report the total number of rainy days for

every month in a year. Get the monthly rainy days from the user one by one and print the total on the screen.

a) In the first program, use twelve variables declared as follows:int Jan, Feb, Mac, Apr, May, Jun;

int Sep, Oct, Nov, Dec;

b) In the second program, use an array of 12 elements as declared below:

int Mon[12];

2. Write a program to analyze the final exam marks for a class of 60 students. Ask the user to get the marks one by one. Then calculate and print on the screen the total and average marks of the students.

BS (May 2012) 17

Page 18: CHAPTER 7: Arrays (Numeric Arrays)

MORE ABOUT ARRAYS

Topic 3

BS (May 2012) 18

Page 19: CHAPTER 7: Arrays (Numeric Arrays)

Passing Arrays to Functions

• In C, passing an array to a function means that the function is granted direct access to all of the elements of that array, not a copy of 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 definition header would

look like?

BS (May 2012) 19

Page 20: CHAPTER 7: Arrays (Numeric Arrays)

Example#include <stdio.h>void displayArray(int s[]); //function prototype

void main(void){

int x[3]={9,7,6};displayArray(x); // function call

}

void displayArray(int s[]) // function definition header{

int i; for (i=0; i<3; i++) printf(“%d\n", s[i]);}

#include <stdio.h>void displayArray(int s[]); //function prototype

void main(void){

int x[3]={9,7,6};displayArray(x); // function call

}

void displayArray(int s[]) // function definition header{

int i; for (i=0; i<3; i++) printf(“%d\n", s[i]);}

BS (May 2012) 20

976

Without array size

Page 21: CHAPTER 7: Arrays (Numeric Arrays)

More Example

BS (May 2012) 21

#include <stdio.h>#define SIZE 5void 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: %.2f\n“, calcAverage(marks));}

#include <stdio.h>#define SIZE 5void 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: %.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]);

}}

void getMarks(float s[ ]){

int i;for (i=0; i<SIZE; i++){

printf("Marks student %d:",i+1);scanf("%f", &s[i]);

}}

float calcAverage(float sc[ ]){

float total = 0.0;int i;for (i=0; i<SIZE; i++){

total = total + sc[i];}return (total / size);

}

float calcAverage(float sc[ ]){

float total = 0.0;int i;for (i=0; i<SIZE; i++){

total = total + sc[i];}return (total / size);

}

Marks student 1: 66Marks student 2: 77Marks student 3: 88Marks student 4: 99Marks student 5: 100Average for marks: 86.00

Page 22: CHAPTER 7: Arrays (Numeric Arrays)

Exercise• Write a program that declares an array of 30 elements named income in the main function.

• Then call and pass the array to a programmer-defined function named getIncome.

• Within the getIncome function, ask the user for annual income of 30 employees. Then, calculate and print the total income on the screen.

• Use the following function prototype in the:

BS (May 2012) 22

void getIncome( ai[]); void getIncome( ai[]);

Page 23: CHAPTER 7: Arrays (Numeric Arrays)

2-DIMENSIONAL (2-D) ARRAYS

Topic 3-2

BS (May 2012) 23

Page 24: CHAPTER 7: Arrays (Numeric Arrays)

2-D Arrays• It is possible to create an array which has

more than one dimension.• In C, we can go up to 12-dimensional arrays.• 2-D arrays (because there are two pairs of []

[]):– Declaration:

• Example:

BS (May 2012) 24

Data_type array[row][column]

int carrymarks[4][2]int carrymarks[4][2]

Row Column

Page 25: CHAPTER 7: Arrays (Numeric Arrays)

2-D: Conceptual View

BS (May 2012) 25

int m[4][2] = {10, 12, 33, 14, 25, 56, 77, 85};int m[4][2] = {10, 12, 33, 14, 25, 56, 77, 85};

Column sizeRow size

10 12

33 14

25 56

77 85

[0] [1]

[0]

[1]

[2]

[3]

Column

Row

This 2D array has 4 rows and 2 columns.

m[0][0] m[0][1] m[1][0] m[1][1] m[2][0] m[2][1] m[3][0] m[3][1]

m

Page 26: CHAPTER 7: Arrays (Numeric Arrays)

Initializing 2-D Arrays2 ways to initialize an array: compile-time and run-time1. Compile-time

– Variable initialization can also be done this way:

– This method is less confusing since we can see the rows and columns division more clearly.

BS (May 2012) 26

int m[4][2] = {{10,12},{33,14},{25,56},{77,85}};int m[4][2] = {{10,12},{33,14},{25,56},{77,85}};

Page 27: CHAPTER 7: Arrays (Numeric Arrays)

Initializing 2-D Arrays2. Run-time• Using nested for statements:

• Although it is possible to create a multi-dimensional array, arrays above 2-dimensions are rarely used.

BS (May 2012) 27

for (row = 0; row < 4; row++) { for (column = 0; column < 2; column++) m[row][column] = 0;}

for (row = 0; row < 4; row++) { for (column = 0; column < 2; column++) m[row][column] = 0;}

Page 28: CHAPTER 7: Arrays (Numeric Arrays)

Passing a 2-D Array to a Function

• 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 m

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.

BS (May 2012) 28

Page 29: CHAPTER 7: Arrays (Numeric Arrays)

Summary• An array is a collection of data of the same type and are used for

the exact same purpose. • The use of an array could provides a shorter and elegant solution.• Dimension of an array is determined by number of [ ] of the array

declaration.• Operations of an array include:

– Declaration – by specifying data type of array element, array name and array size.

– Initialize and assign values to arrays elements at: compile-time and run-time– To read and display value from an array element, refer to the position number

(or index).– Passing arrays to a function require you to deal with the function prototype,

function call and function definition header .

BS (May 2012) 29