Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 13 & 14 Arrays SCK1213Programming Technique I SEM1 2009/2010

Similar presentations


Presentation on theme: "Week 13 & 14 Arrays SCK1213Programming Technique I SEM1 2009/2010"— Presentation transcript:

1 Week 13 & 14 Arrays SCK1213Programming Technique I SEM1 2009/2010
Source from Tony Gaddis, Barret Krupnow, Starting out with C++, 5th edition update Pearson Addison-Wesley

2 Arrays Hold Multiple Values
7.1 Arrays Hold Multiple Values

3 Arrays Hold Multiple Values
Array: variable that can store multiple values of the same type – vs. ordinary variable which can only contains a single value Values are stored in adjacent memory locations Declared using [] operator: int tests[5];

4 Concept of an array A single value in an array is called an element
An index (or a subscript) is a reference of an element It is an integer number Index 0 refers to the first element

5 allocates the following memory:
Array - Memory Layout The definition: int tests[5]; allocates the following memory: first element second element third element fourth element fifth element

6 Array Terminology In the definition int tests[5]; int is the data type of the array elements tests is the name of the array 5, in [5], is the size declarator. It shows the number of elements in the array. The size of an array is (number of elements) * (size of each element)

7 Array Terminology The size of an array is: Examples:
the total number of bytes allocated for it (number of elements) * (number of bytes for each element) Examples: int tests[5] is an array of 20 bytes, assuming 4 bytes for an int long double measures[10]is an array of 80 bytes, assuming 8 bytes for a long double

8 Size Declarators Named constants are commonly used as size declarators. const int SIZE = 5; int tests[SIZE]; This eases program maintenance when the size of the array needs to be changed.

9 There are 2 things to do when using arrays:
Declaration and definition of arrays Accessing elements in arrays (in 7.2) For assigning values For getting values

10 Declaring and Defining Arrays
Since an array is a variable, it must be declared and defined before it can used Declaration and definition tell the compiler: The name of the array The data type of each element The number of elements in the array Syntax: data_type variable_name[n]; //n = no. of elements

11 Declaring and Defining Arrays

12 Declaring and Defining Arrays
Like ordinary variable, arrays may also be initialized (more on slide #27):

13 Accessing Array Elements
7.2 Accessing Array Elements

14 Accessing Array Elements
Each element in an array is assigned a unique subscript. Subscripts start at 0 subscripts: 1 2 3 4

15 Accessing Array Elements
The last element’s subscript is n-1 where n is the number of elements in the array. subscripts: 1 2 3 4

16 Accessing Array Elements
Array elements can be used as regular variables: tests[0] = 79; printf (“%d”, tests[0]); scanf (“%d”, &tests[1]); tests[4] = tests[0] + tests[1]; Arrays must be accessed via individual elements: printf (“%d”, tests); // not legal

17 Accessing Array Elements - example
/* This program asks for the number of hours worked by six employees. It stores the values in an array. */ #include <stdio.h> #include <conio.h> int main () { const int NUM_EMPLOYEES = 6; int hours [NUM_EMPLOYEES]; /* Get the hours worked by six employees */ printf ("Enter the hours worked by six employees: "); scanf ("%d", &hours[0]); scanf ("%d", &hours[1]); scanf ("%d", &hours[2]); scanf ("%d", &hours[3]); scanf ("%d", &hours[4]); scanf ("%d", &hours[5]); (Program Continues)

18 Accessing Array Elements - example
/* Display the values in the array */ printf ("The hours you entered are: "); printf ("%d ", hours[0]); printf ("%d ", hours[1]); printf ("%d ", hours[2]); printf ("%d ", hours[3]); printf ("%d ", hours[4]); printf ("%d ", hours[5]); getch(); return 0; } Here are the contents of the hours array, with the values entered by the user in the example output:

19 Accessing Array Contents
Can access element with a constant or literal subscript: printf (“%d \n”, tests[3]); Can use integer expression as subscript: int i = 5; printf (“%d \n”, tests[i]);

20 Examples Assigning variable n with the value of first element of an array A int A[] = {1, 3, 5, 7} int n; n = A[0]; Printing the second element of an array B int B[] = {10, 30, 50, 70} printf (“%d”, B[1]);

21 Examples cont. 3. Assigning the first element of array C with the value of the second element int C[] = {11, 23, 35, 47}; C[0] = C[1]; 4. Printing all elements of an array D int D[] = {1, 4, 3, 6, 7, 8, 9, 0, 2} int i; for (i=0; i<9; i++) printf (“%d\n”, D[i]);

22 Using a Loop to Step Through an Array
Example – The following code defines an array, numbers, and assigns 99 to each element: const int ARRAY_SIZE = 5; int numbers[ARRAY_SIZE]; for (int count = 0; count < ARRAY_SIZE; count++) numbers[count] = 99;

23 A Closer Look At the Loop

24 Default Initialization
Global array  all elements initialized to 0 by default Local array  all elements uninitialized by default

25 Exercise Week 13_1 Refer to Lab 12, Exercise 1 No. 1 in pg Discuss

26 7.3 Array Initialization

27 Array Initialization Arrays can be initialized with an initialization list: const int SIZE = 5; int tests[SIZE] = {79,82,91,77,84}; The values are stored in the array in the order in which they appear in the list. The initialization list cannot exceed the array size.

28 Code From Program 7-6 printf (“Month %d has “, (count + 1));
printf (“%d days.\n”, days[count]);

29 Partial Array Initialization
If array is initialized with fewer initial values than the size declarator, the remaining elements will be set to 0:

30 Can determine array size by the size of the initialization list:
Implicit Array Sizing Can determine array size by the size of the initialization list: int quizzes[]={12,17,15,11}; Must use either array size declarator or initialization list at array definition 12 17 15 11

31 Initializing With a String
Character array can be initialized by enclosing string in " ": const int SIZE = 6; char fName[SIZE] = "Henry"; Must leave room for \0 at end of array If initializing character-by-character, must add in \0 explicitly: char fName[SIZE] = { 'H', 'e', 'n', 'r', 'y', '\0'};

32 Correct the errors in the following program. What is missing?
Exercise Week 13_2 Correct the errors in the following program. What is missing? #include <stdio.h> int main(){ int SIZE=5; int arr[SIZE]; // to store value in arr for (int i=1;i<=5;i++) arr[i]=i*i; printf ("arr5=%d”, arr[5]); return 0; }

33 Exercise Week 13_3 Are each of the following valid or invalid array definitions? (If a definition is invalid, explain why) int numbers[l0] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 1}; int matrix[5] = {1, 2, 3, 4, 5, 6, 7}; double radix[10] = {3.2, 4.7}; int table[7] = {2, , , 27, , 45, 39}; char codes [] = {‘A', 'X', '1', '2', 's'}; int blanks[]; char name[6] = "Joanne"; Refer to Lab 12, Exe. 1, No. 4i-v in pg. 114. Solve the problem

34 Processing Array Contents
7.4 Processing Array Contents

35 Processing Array Contents
Array elements can be treated as ordinary variables of the same type as the array When using ++, -- operators, don’t confuse the element with the subscript: tests[i]++; // add 1 to tests[i] tests[i++]; // increment i, no // effect on tests

36 Given the following array definition: int values[] = {2, 6, 10, 14};
Exercise Week 13_4 Given the following array definition: int values[] = {2, 6, 10, 14}; What do each of the following display? printf (“%d”, values[2]); b. printf (“%d”, ++values[0]); c. printf (“%d”, values[1]++); d. x = 2; printf (“%d”, values[++x]);

37 To copy one array to another,
Array Assignment To copy one array to another, Don’t try to assign one array to the other: newTests = tests; // Won't work Instead, assign element-by-element: for (i = 0; i < ARRAY_SIZE; i++) newTests[i] = tests[i];

38 Printing the Contents of an Array
You can display the contents of a character array by sending its name to printf: char fName[] = "Henry"; printf (“%c\n”, fName); But, this ONLY works with character arrays!

39 Printing the Contents of an Array
For other types of arrays, you must print element-by-element: for (i = 0; i < ARRAY_SIZE; i++) printf (“%d\n”, tests[i]);

40 Summing and Averaging Array Elements
Use a simple loop to add together array elements: int tnum; double average, sum = 0; for(tnum = 0; tnum < SIZE; tnum++) sum += tests[tnum]; Once summed, can compute average: average = sum / SIZE;

41 Finding the Highest Value in an Array
int count; int highest; highest = numbers[0]; for (count = 1; count < SIZE; count++) { if (numbers[count] > highest) highest = numbers[count]; } When this code is finished, the highest variable will contain the highest value in the numbers array.

42 Finding the Lowest Value in an Array
int count; int lowest; lowest = numbers[0]; for (count = 1; count < SIZE; count++) { if (numbers[count] < lowest) lowest = numbers[count]; } When this code is finished, the lowest variable will contain the lowest value in the numbers array.

43 Partially-Filled Arrays
If it is unknown how much data an array will be holding: Make the array large enough to hold the largest expected number of elements. Use a counter variable to keep track of the number of items stored in the array.

44 To compare two arrays, you must compare element-by-element:
Comparing Arrays To compare two arrays, you must compare element-by-element: const int SIZE = 5; int firstArray[SIZE] = { 5, 10, 15, 20, 25 }; int secondArray[SIZE] = { 5, 10, 15, 20, 25 }; int arraysEqual = 1; // TRUE condition int count = 0; // Loop counter variable // Compare the two arrays. while (arraysEqual && count < SIZE) { if (firstArray[count] != secondArray[count]) arraysEqual = 0; count++; } if (arraysEqual) printf ("The arrays are equal.\n”); else printf ("The arrays are not equal.\n”);

45 Exercise Week 13_5 Refer to Lab 12, Exercise , 2 No. 2i-iii in pg Solve the problem

46 7.5 Using Parallel Arrays

47 Using Parallel Arrays Parallel arrays: two or more arrays that contain related data A subscript is used to relate arrays: elements at same subscript are related Arrays may be of different types

48 Parallel Array Example
const int SIZE = 5; // Array size int id[SIZE]; // student ID double average[SIZE]; // course average char grade[SIZE]; // course grade ... for(int i = 0; i < SIZE; i++) { printf ("Student ID: %d average: %d grade: \n", id[i], average[i], grade[i]) }

49 Parallel Array Example – Program 7.12
/* This program stores, in an array, the hours worked by 5 employees who all make the same hourly wage. */ #include <stdio.h> #include <conio.h> int main() { const int NUM_EMPLOYEES = 5; int hours [NUM_EMPLOYEES]; /* hold hours worked */ double payRate [NUM_EMPLOYEES]; /* holds pay rate */ /* Input the hours worked */ printf ("Enter the hours worked by %d", NUM_EMPLOYEES); printf (" employees and their\n"); printf ("hourly pay rates.\n"); for (int index = 0; index < NUM_EMPLOYEES; index++) printf ("Hours worked by employees # %d :", (index + 1)); scanf ("%d", &hours[index]); printf ("Hourly pay rate for employee # %d :", (index + 1)); scanf ("%lf", &payRate[index]); } Parallel Array Example – Program 7.12 /* This program stores, in an array, the hours worked by 5 employees who all make the same hourly wage. */ #include <stdio.h> #include <conio.h> int main() { const int NUM_EMPLOYEES = 5; int hours [NUM_EMPLOYEES]; /* hold hours worked */ double payRate [NUM_EMPLOYEES]; /* holds pay rate */ /* Input the hours worked */ printf ("Enter the hours worked by %d", NUM_EMPLOYEES); printf (" employees and their\n"); printf ("hourly pay rates.\n"); for (int index = 0; index < NUM_EMPLOYEES; index++) printf ("Hours worked by employees # %d :", (index + 1)); scanf ("%d", &hours[index]); printf ("Hourly pay rate for employee # %d :", (index + 1)); scanf ("%lf", &payRate[index]); } (Program Continues)

50 Parallel Array Example – program 7.12 cont.
/* Display each employee's gross pay */ printf ("Here is the gross pay for each employee:\n"); for (int index = 0; index < NUM_EMPLOYEES; index++) { double grossPay = hours[index] * payRate[index]; printf ("Employee # %d", (index + 1)); printf (": $ %.2lf\n", grossPay); } getch(); return 0;

51 Parallel Array Example
The hours and payRate arrays are related through their subscripts:

52 Exercise Week 13_6 What is the output of the following code? (You may need to use a calculator.) . const int SIZE = 5; int time[SIZE] = {1, 2, 3, 4, 5}, speed[SIZE] = {18, 4, 27, 52, 100}, dist[SIZE]; for (int count = 0; count < SIZE; count++) dist[count] = time[count] * speed[count]; for (int count = 0; count < SIZE; count++) { printf (“%d ”, time[count]); printf (“%d ”, speed[count]); printf (“%d\n”, dist[count]); }

53 Arrays as Function Arguments
7.6 Arrays as Function Arguments

54 Passing an element of an array to a function can be in two forms:
Arrays and Functions Passing an element of an array to a function can be in two forms: Pass by value – pass its content: e.g. printf (“%d”, A[2]); Pass by reference – pass its address: e.g. scanf (“%d”, &A[2]);

55 Arrays and Functions Passing the whole array to a function can only be done by using pass by reference It usually passes the address of the first element Example: void increase (int x[3]) { x[0] += 1; x[1] += 2; x[2] += 3; } void main (void) int A[3] = {10, 20, 30}; increase (A); /* or, increase (&A[0]);

56 Arrays as Function Arguments
To pass an array to a function, just use the array name: showScores(tests); To define a function that takes an array parameter, use empty [] for array argument: void showScores(int []); // function prototype void showScores(int tests[]) // function header

57 Arrays as Function Arguments
When passing an array to a function, it is common to pass array size so that function knows how many elements to process: showScores(tests, ARRAY_SIZE); Array size must also be reflected in prototype, header: void showScores(int [], int); // function prototype void showScores(int tests[], int size) // function header

58 Arrays as Function Arguments - example
#include <stdio.h> (Program Continues)

59 Program 7-14 (Continued) Arrays as Function Arguments - example
printf ("%d ", nums[index]); printf ("\n");

60 Modifying Arrays in Functions
Array names in functions are like reference variables – changes made to array in a function are reflected in actual array in calling function Need to exercise caution that array is not inadvertently changed by a function

61 Exercise Week 13_7 The following program skeleton, when completed, will ask the user to enter 10 integers which are stored in an array. The function avgArray, which you must write, is to calculate and return the average of the numbers entered. #include <stdio.h> //Write your function prototype here int main() { const int SIZE = 10; int userNums[SIZE]; printf ("Enter 10 numbers: ”); for (int count = 0; count < SIZE; count++){ printf ("#%d ", (count + 1)); scanf (“%d”, &userNums[count]); } printf ("The average of those numbers is ”); int avg = avgArray(userNUms, SIZE); printf (”%d\n”, avg); return 0; //Write the function avgArray here.

62 Two-Dimensional Arrays
7.7 Two-Dimensional Arrays

63 Two-Dimensional Arrays
Can define one array for multiple sets of data Like a table in a spreadsheet Use two size declarators in definition: const int ROWS = 4, COLS = 3; int exams[ROWS][COLS]; First declarator is number of rows; second is number of columns

64 Two-Dimensional Array Representation
const int ROWS = 4, COLS = 3; int exams[ROWS][COLS]; Use two subscripts to access element: exams[2][2] = 86; columns exams[0][0] exams[0][1] exams[0][2] exams[1][0] exams[1][1] exams[1][2] exams[2][0] exams[2][1] exams[2][2] exams[3][0] exams[3][1] exams[3][2] r o w s

65 Two-Dimensional Array Representation - Example
/* This program demostrates a two-dimensional array */ #include <stdio.h> #include <conio.h> int main() { const int NUM_DIVS = 3; /* Number of divisions */ const int NUM_QTRS = 4 ; /* Number of quarters */ double sales[NUM_DIVS][NUM_QTRS]; /* Array with 3 rows and 4 columns */ double totalSales =0; /* To hold the total sales */ int div, qtr; printf ("This program will calculate the total sales of\n"); printf ("all the company's divisions.\n"); printf ("Enter the following sales information:\n\n"); (Program continues)

66 Two-Dimensional Array Representation - Example
/* Nested loops to fill the array quarterly sales figures for each divisions */ for (div = 0; div < NUM_DIVS; div++) { for (qtr = 0; qtr < NUM_QTRS; qtr++) printf ("Division %d", (div + 1)); printf (", Quarter %d: $", (qtr + 1)); scanf ("%lf", &sales[div][qtr]); } printf ("\n"); /* Print blank line */ /* Nested loops used to add all the elements */ for (qtr = 0; qtr <NUM_QTRS; qtr++) totalSales += sales[div][qtr]; printf ("The total sales for the company are: $"); printf ("%.2lf\n", totalSales); getch(); return 0;

67 Two-Dimensional Array Representation - Example

68 2D Array Initialization
Two-dimensional arrays are initialized row-by-row: const int ROWS = 2, COLS = 2; int exams[ROWS][COLS] = { {84, 78}, {92, 97} }; Can omit inner { }, some initial values in a row – array elements without initial values will be set to 0 or NULL 84 78 92 97

69 Two-Dimensional Array as Parameter, Argument
Use array name as argument in function call: getExams(exams, 2); Use empty [] for row, size declarator for column in prototype, header: const int COLS = 2; // Prototype void getExams(int [][COLS], int); // Header void getExams(int exams[][COLS], int rows)

70 Example – The showArray Function from Program 7-19
printf ("%4d ", array[x][y]); } printf ("\n");

71 How showArray is Called
printf (“The contents of table1 are:\n”); showArray (table1, TBL1_ROWS); printf (“The contents of table2 are:\n”); showArray (table2, TBL2_ROWS);

72 Summing All the Elements in a Two-Dimensional Array
Given the following definitions: const int NUM_ROWS = 5; // Number of rows const int NUM_COLS = 5; // Number of columns int total = 0; // Accumulator int numbers[NUM_ROWS][NUM_COLS] = {{2, 7, 9, 6, 4}, {6, 1, 8, 9, 4}, {4, 3, 7, 2, 9}, {9, 9, 0, 3, 1}, {6, 2, 7, 4, 1}};

73 Summing All the Elements in a Two-Dimensional Array
// Sum the array elements. for (int row = 0; row < NUM_ROWS; row++) { for (int col = 0; col < NUM_COLS; col++) total += numbers[row][col]; } // Display the sum. printf ("The total is %d\n", total);

74 Summing the Rows of a Two-Dimensional Array
Given the following definitions: const int NUM_STUDENTS = 3; const int NUM_SCORES = 5; double total; // Accumulator double average; // To hold average scores double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94}, {86, 91, 78, 79, 84}, {82, 73, 77, 82, 89}};

75 Summing the Rows of a Two-Dimensional Array
// Get each student's average score. for (int row = 0; row < NUM_STUDENTS; row++) { // Set the accumulator. total = 0; // Sum a row. for (int col = 0; col < NUM_SCORES; col++) total += scores[row][col]; // Get the average average = total / NUM_SCORES; // Display the average. printf ("Score average for student %d is %lf\n", (row + 1), average); }

76 Summing the Columns of a Two-Dimensional Array
Given the following definitions: const int NUM_STUDENTS = 3; const int NUM_SCORES = 5; double total; // Accumulator double average; // To hold average scores double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94}, {86, 91, 78, 79, 84}, {82, 73, 77, 82, 89}};

77 Summing the Columns of a Two-Dimensional Array
// Get the class average for each score. for (int col = 0; col < NUM_SCORES; col++) { // Reset the accumulator. total = 0; // Sum a column for (int row = 0; row < NUM_STUDENTS; row++) total += scores[row][col]; // Get the average average = total / NUM_STUDENTS; // Display the class average. printf ("Class average for test %d is %lf\n", (col + 1), average); }

78 Exercise Week 13_8 Refer to Lab 13, Exe. 1, No. 1i-iii in pg. 121-122.
Solve the problem Change the program to define the following arrays & print the elements (questions are independent). Define a two-dimensional array named settings large enough to hold the table of data below. Initialize the array with the values in the table. int table[3][4] = {{2, 3}, {7, 9, 2}, {1}}; Print the sum of the same locations numbers in the two arrays. 12 78 45 1 14 34 56 66 17 67 8

79 7.8 Array of Strings

80 Each row contains one string
Array of Strings Use a two-dimensional array of characters as an array of strings: const int NAMES = 3, SIZE = 10; char students[NAMES][SIZE] = { "Ann", "Bill", "Cindy" }; Each row contains one string Can use row subscript to reference the string in a particular row: printf (“%d”, students[i]);

81 Array of Strings - example
/* This program displays the number of days in each month */ #include <stdio.h> #include <conio.h> int main() { const int NUM_MONTHS = 12; /* The number of months */ const int STRING_SIZE = 10; /* Maximum size of each string */ /* Array with the names of the months */ char months[NUM_MONTHS][STRING_SIZE] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; /* Array with the number of days in each month */ int days [NUM_MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

82 Array of Strings /* Display the months and their numbers of days */
for (int count = 0; count < NUM_MONTHS; count++) { printf ("%s has ", months[count]); printf ("%d days.\n", days[count]); } getch(); return 0;

83 Exercise Week 13_9 Define an array of strings to store the name of your friends in this class. Initialize the array with 5 names. Print the names. Write a function to change the names in the array. void changeName(char [][25], int size);

84 Arrays with Three or More Dimensions
7.9 Arrays with Three or More Dimensions

85 Arrays with Three or More Dimensions
Can define arrays with any number of dimensions: short rectSolid[2][3][5]; double timeGrid[3][4][3][4]; When used as parameter, specify all but 1st dimension in prototype, heading: void getRectSolid(short [][3][5]);

86 Thank You Q & A


Download ppt "Week 13 & 14 Arrays SCK1213Programming Technique I SEM1 2009/2010"

Similar presentations


Ads by Google