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

week13_14Array-revC

Embed Size (px)

DESCRIPTION

c programming notes; array

Citation preview

  • SCK1213Programming Technique ISEM1 2009/2010ArraysWeek 13 & 14Source from Tony Gaddis, Barret Krupnow, Starting out with C++, 5th edition update. 2007. Pearson Addison-Wesley

  • Arrays Hold Multiple Values7.1

  • Arrays Hold Multiple ValuesArray: variable that can store multiple values of the same type vs. ordinary variable which can only contains a single valueValues are stored in adjacent memory locationsDeclared using [] operator:int tests[5];

  • Concept of an arrayA single value in an array is called an elementAn index (or a subscript) is a reference of an elementIt is an integer numberIndex 0 refers to the first element

  • Array - Memory LayoutThe definition: int tests[5];allocates the following memory:

    first elementsecond elementthird elementfourth elementfifth element

  • Array TerminologyIn the definition int tests[5];int is the data type of the array elementstests is the name of the array5, 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)

  • Array TerminologyThe size of an array is: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 intlong double measures[10]is an array of 80 bytes, assuming 8 bytes for a long double

  • Size DeclaratorsNamed 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.

  • Using ArraysThere are 2 things to do when using arrays:Declaration and definition of arraysAccessing elements in arrays (in 7.2)For assigning valuesFor getting values

  • Declaring and Defining ArraysSince 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 arrayThe data type of each elementThe number of elements in the array

    Syntax:data_type variable_name[n]; //n = no. of elements

  • Declaring and Defining Arrays

  • Declaring and Defining ArraysLike ordinary variable, arrays may also be initialized (more on slide #27):

  • Accessing Array Elements7.2

  • Accessing Array ElementsEach element in an array is assigned a unique subscript.Subscripts start at 0

    subscripts:

    01234

  • Accessing Array ElementsThe last elements subscript is n-1 where n is the number of elements in the array.subscripts:

    01234

  • Accessing Array ElementsArray 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

  • (Program Continues)Accessing Array Elements - example/* This program asks for the number of hours worked by six employees. It stores the values in an array. */

    #include #include

    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]);

  • Here are the contents of the hours array, with the values entered by the user in the example output: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;}

  • Accessing Array ContentsCan 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]);

  • ExamplesAssigning variable n with the value of first element of an array Aint 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]);

  • 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

  • Using a Loop to Step Through an ArrayExample 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;

  • A Closer Look At the Loop

  • Default InitializationGlobal array all elements initialized to 0 by default Local array all elements uninitialized by default

  • Exercise Week 13_1Refer to Lab 12, Exercise 1 No. 1 in pg. 111-112.Discuss

  • Array Initialization7.3

  • Array InitializationArrays 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.

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

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

  • Implicit Array SizingCan 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

    12171511

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

  • Exercise Week 13_2Correct the errors in the following program. What is missing? #include

    int main(){ int SIZE=5; int arr[SIZE];

    // to store value 1 4 9 16 25 in arr for (int i=1;i

  • Exercise Week 13_3Are 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

  • Processing Array Contents7.4

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

  • Exercise Week 13_4Given 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]);

  • Array AssignmentTo copy one array to another,Dont 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];

  • Printing the Contents of an ArrayYou 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!

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

  • Summing and Averaging Array ElementsUse 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;

  • Finding the Highest Value in an Arrayint 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.

  • Finding the Lowest Value in an Arrayint 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.

  • Partially-Filled ArraysIf 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.

  • Comparing ArraysTo 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 conditionint 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);

  • Exercise Week 13_5Refer to Lab 12, Exercise , 2 No. 2i-iii in pg. 116-117.Solve the problem

  • Using Parallel Arrays7.5

  • Using Parallel ArraysParallel arrays: two or more arrays that contain related dataA subscript is used to relate arrays: elements at same subscript are relatedArrays may be of different types

  • Parallel Array Exampleconst int SIZE = 5; // Array sizeint id[SIZE]; // student IDdouble average[SIZE]; // course averagechar 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]) }

  • 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 #include

    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]); }/* This program stores, in an array, the hours worked by 5 employees who all make the same hourly wage. */

    #include #include

    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)

  • 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; }

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

  • Exercise Week 13_6What 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]); }

  • Arrays as Function Arguments7.6

  • Arrays and FunctionsPassing 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]);

  • Arrays and FunctionsPassing the whole array to a function can only be done by using pass by referenceIt 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]);

  • Arrays as Function ArgumentsTo 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 prototypevoid showScores(int tests[]) // function header

  • Arrays as Function ArgumentsWhen 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 prototypevoid showScores(int tests[], int size) // function header

  • (Program Continues)Arrays as Function Arguments - example#include

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

  • Modifying Arrays in FunctionsArray 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

  • Exercise Week 13_7The 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 //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.

  • Two-Dimensional Arrays7.7

  • Two-Dimensional ArraysCan define one array for multiple sets of dataLike a table in a spreadsheetUse 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

  • Two-Dimensional Array Representation const int ROWS = 4, COLS = 3; int exams[ROWS][COLS];

    Use two subscripts to access element:exams[2][2] = 86;columnsrows

    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]

  • Two-Dimensional Array Representation - Example/* This program demostrates a two-dimensional array */#include #include

    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)

  • 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 (div = 0; div < NUM_DIVS; div++) { for (qtr = 0; qtr

  • Two-Dimensional Array Representation - Example

  • 2D Array InitializationTwo-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

    84789297

  • Two-Dimensional Array as Parameter, ArgumentUse 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)

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

  • How showArray is Calledprintf (The contents of table1 are:\n);showArray (table1, TBL1_ROWS);printf (The contents of table2 are:\n);showArray (table2, TBL2_ROWS);

  • Summing All the Elements in a Two-Dimensional ArrayGiven the following definitions:const int NUM_ROWS = 5; // Number of rowsconst int NUM_COLS = 5; // Number of columnsint total = 0; // Accumulatorint 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}};

  • 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);

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

  • 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);}

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

  • 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);}

  • Exercise Week 13_8Refer to Lab 13, Exe. 1, No. 1i-iii in pg. 121-122.Solve the problemChange 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.

    1278451143456664517678

  • Array of Strings7.8

  • Array of StringsUse 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]);

  • Array of Strings - example/* This program displays the number of days in each month */#include #include

    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};

  • 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; }

  • Exercise Week 13_9Define 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);

  • Arrays with Three or More Dimensions7.9

  • Arrays with Three or MoreDimensionsCan 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]);

  • Thank You

    Q & A