Topic Arrays

download Topic Arrays

of 29

Transcript of Topic Arrays

  • 8/13/2019 Topic Arrays

    1/29

    INTRODUCTIONA computer is a machine that manipulates information. The study ofInformation Technology/Computer Science therefore, inevitably, includes thestudy of how information is organised in a computer, how it can be manipulatedand how it can be utilised. Thus, it is exceedingly important to understand theconcept of information organisation and manipulation.

    A computer is referred to as a data processing machine using which raw data isprocessed to get it transformed into refined data, and this transformation is donethrough algorithms. Therefore, we can say that raw data is input and algorithmsare used to transform it into refined data. The way in which the data can be

    processed depends on the structures that are used for representation of data. Thealgorithms that we can use to process the data depend on the structure used forthe representation of data. Therefore, it becomes necessary to study the variousstructures for the representation of data and the algorithms that operate on thesestructures. Knowing the structures, one can think of the various alternativerepresentations of the data and the corresponding operations operating on themand choose the one that is better suited to the requirement.

    TTooppiicc

    11 Arrays

    LEARNING OUTCOMES

    By the end of this topic, you should be able to:

    1. Declare and perform manipulations on one-dimensional arrays andtwo-dimensional arrays;

    2. Solve programming problems using one-dimensional arrays andtwo-dimensional arrays; and

    3. Solve programming problems using arrays that involve functions.

  • 8/13/2019 Topic Arrays

    2/29

    TOPIC 1 ARRAYS2

    The study of different structures for representation of data and the algorithmsthat operate on these structures constitute what we call study of data structures.

    A "data structure"which displays the relationship of adjacency between elementsis said to be "linear". This type of data structure is used to represent one of thesimplest and most commonly found data object i.e. ordered or linear list.

    Examples are months of the year

    [January, February, March.............., December]

    or the values in a card deck.

    [2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace]

    or a group of friends

    [Sudha, Sze Hong, Neeraj, Azim, Dixie].

    If we consider an ordered list more abstractly, we say that it is either empty or itcan be written as

    [x1, x2, x3......xn]

    where xi's are atoms or elements from some set A.

    There are a variety of operations that can be performed on linear data structures.These operations include:

    (a) Find the length of the list, n;(b) Read the list from left to right or (right to left);(c) Retrieve the ithelement of the list, 1 n;(d) Store a new value into the ithposition, 1 n;(e) Insert a new element at position i, 1in causing elements numbered i,

    i+1......, n to become numbered i+1, i+2....n+1; and

    (f) Delete the element at position i, 1in causing elements numbered i+1,...nto become numbered i, i+1,....n-1.

    The simplest linear data structure that makes use of computed addresses tolocate its elements is the one dimensional array.

    This topic will discuss the concept of arrays, one-dimensional arrays and two-dimensional arrays, and how to use them in programming. Therefore, are youready? If so, then let us proceed to explore all that is related to arrays.

  • 8/13/2019 Topic Arrays

    3/29

    TOPIC 1 ARRAYS 3

    CONCEPT OF ARRAY

    Do you still remember variables? Can you compare the concept of variables andarrays?

    Why do we need arrays in our programming? This question can be answered bygiving an example. Let us say that you would like to keep a record of yourpersonal spending for the year 2002. You can file all your receipts and details ofexpenditure in multiple files according to the month. This means that you have12 different files. However, would not it be easier if you could manage a singlefile with 12 compartments?

    Let us relate this scenario to computer programming. Let us just say that wewould like to write a program to manage your expenses. Your program candeclare 12 separate variables to represent the total monthly expenditure (just likehow we would use 12 files to store the receipts). However, we could furtherimprove our program by using an array that has 12 elements, that is, by storing

    the monthly total spending in each of the array elements.

    ONE-DIMENSIONAL ARRAYS

    A one-dimensional array is an array that has only one index or subscript. Anindex is a value that is written in the brackets [ ] after an array name. An indexcan identify the number of elements in an array. This is explained in thefollowing section.

    1.2.1 Declaring Arrays

    It is easy to declare an array. We can use the same method that we use to declarenormal variables, but the difference lies in that the name of the array mustinclude the array size specification (which is enclosed by the [ and ] symbols). Ingeneral, we can declare one-dimensional arrays as follows:

    data_t ype arr ay_name[number_of _el ement s] ;

    Arraysare data structures that contain data items of the same type. Arraysalso contain static data. This means that the size of the array is fixed from thedeclaration all the way to the final program implementation.

    1.2

    1.1

  • 8/13/2019 Topic Arrays

    4/29

    TOPIC 1 ARRAYS4

    which:

    dat a_t ype - type of data that will be stored in the array

    ar r ay_name - the name of the arraynumber _of _el ement s - a positive integer that indicates how manyelements should be stored in memory

    The value of number_of_elements will decide the number of data values that canbe stored in the array. The number of this data values can also be referred to asarray size.Let us have a look at the following example of array declaration:

    i nt number [ 10] ;

    The above statement will declare an array that is called number and is of size10. This declaration will instruct the compiler to reserve 10 memory spaces insequence that can be referred asnumber . This sequence of memory spaces is alsoknown as array elements. Since the dat a_t ypefor number is declared as beingthe i nt type, therefore, the number array elements can contain data of i nt typeonly. Observe the illustration in Figure 1.1.

    Figure 1 1:Illustration of memory location for the declaration of i nt number[ 10]The value within the [ ] brackets is also known as the array index. The arrayindex always begins with 0 and ends with the size of the array subtracted by 1. Inthe above example, the array index of number begins with 0 and ends with 9.With this, the array element values can be referred to as number[ 0] ,number [ 1] , . . . number [ 9] . The array size must be an integer and consistsof an expression and the expression is evaluated to determine the index. If a

  • 8/13/2019 Topic Arrays

    5/29

    TOPIC 1 ARRAYS 5

    program uses an expression as an index, then the expression is evaluated todetermine the index. For example, if a = 5 and b=6, then the statement:

    Arrays may be declared to contain other data types. For example, an array oftype h rcan be used to store a character string.

    To enhance your understanding in the subject, do the following exercise.

    Draw a memory location as reference for each element of the arraysthat are declared as follows:

    char t ext [ 80] ; / *char act er ar r ay of si ze 80*/i nt mar ks[ 100] ; / *i nt eger ar r ay of si ze 100*/f l oat hi gh[ 5] ; / *r eal number ar r ay of si ze 5*/

    What can you conclude from the illustration of the above arrays? Howabout the float high[5.5];?

    ACTIVITY 1.1

    Declare a suitable array for each of the following:

    (a) An array for 30 real numbers(b) An array for a sequence of 126 characters

    SELF-CHECK 1.1

  • 8/13/2019 Topic Arrays

    6/29

    TOPIC 1 ARRAYS6

    1.2.2 Initialising Array Elements

    As for normal variables, we can also set the initial values for each array element

    during declaration. See Figure 1.2.

    i nt di gi t [ 10] = {7, 5, 3, 8, 0, 9, 2, 4, 1, 6};

    Array with Initial Values

    Figure 1 2:Array initialisation and memory location illustrationAll the array elements that are not given initial values will be set with the valueof 0 automatically. See the following example:

    i nt di gi t 1[ 10] = {1, 2, 3};

    The result is the di gi t 1array will have the following sequential values:

    Array without Full Initial Values

    Figure 1 3:Partial initialisation of elements and memory location illustrationAnother easy way of declaring is by listing the initial values of the elements,without declaring the size of the array. Have a look at the following arraydeclaration. Here, the size of the di gi t2 array is 5, based on the number ofelements in the initial value list.

    i nt di gi t 2[ ] = { 1, 2, 3, 4, 5 } ;

  • 8/13/2019 Topic Arrays

    7/29

    TOPIC 1 ARRAYS 7

    In order to ensure that you understand what has been taught, answer thefollowing questions.

    1.2.3 Assigning and Accessing Array Elements

    We have looked at the array index that enables us to differentiate every elementin an array. The array index also enables us to refer to the element in an array.For example, we shall look at the digit array declaration again:

    i nt di gi t [ 10] = {7, 5, 3, 8, 0, 9, 2, 4, 1, 6}

    We can refer to the first array element as di gi t [ 0] , fifth element as di gi t [ 4] , and so on. Here, observe that the value of di gi t [ 0] is 7 while the value ofdi gi t [ 4] is 0.

    Figure 1 4:Memory element of di gi t array

    Draw a diagram that illustrates the memory location for the

    declaration of thedi gi t2array.

    ACTIVITY 1.2

    Write a suitable array declaration for each of the following:

    (a)

    Declare a one-dimensional integer array of size 12 that is calledodd. Assign the values 1, 3, 5, 6, ..., 23 to the elements of that array.

    (b) Declare a one-dimensional real number array of size 6 that is calledconst ant . Assign the following values to the array elements:

    0.02, -0.45, 5.77, -2.55, 7.50, -5

    SELF-CHECK 1.2

  • 8/13/2019 Topic Arrays

    8/29

    TOPIC 1 ARRAYS8

    We can assign any data values for each of the array element that has beendefined by using the assignment statement. However, the value that is assignedmust be the same data type with the type of data contained within the array.

    Look at the following example. In this example, we declared the di gi t arraywithout initial values. Each following assignment statement assigns values to thearray element. As a result we will have an array that is the same array as inFigure 1.4.

    i nt mont h[ 10] ; / * decl ar e mont h ar r ay of si ze 10 */mont h[ 0] = 7; / * assi gn 7 t o t he f i r st el ement */mont h[1] = 5; / * assi gn 5 t o t he second el ement */mont h[ 2] = 3; / * assi gn 3 t o t he t hi r d el ement */

    Can you note down the values that are assigned based on

    i nt mont h[ 10] = {7, 5, 3, 8, 0, 9, 2, 4, 1, 6};

    mont h[ 3] = ?mont h[ 4] = ?

    :mont h[ 9] = ?

    Assigning values to array elements is the same as assigning values to a variable.The difference is that we need to state the array index that is being referenced.

    Just like normal assignment statements, the right hand side part of theassignment statement for the array element can also be an expression. Look at thefollowing example:

    i nt X[ 3] ; / * ar r ay decl ar at i on of 3 el ement s */X[ 0] = 2; / * assi gn 2 t o X[ 0] */X[ 1] = 3 + 4; / * assi gn ( 3 + 4) expr essi on t o X[ 1] */X[ 2] = 5 * 6; / * assi gn ( 5 *6) expr essi on t o X[ 2] */

    The expression on the right of the assignment statement can also contain

    elements of the same array. Look at the following example. The values that areassigned in these assignment statements are explained in Figure 1.5.

    i nt Y[ 5] ; / * ar r ay decl ar at i on of 5 el ement s */Y[ 0] = 1; / * ass i gn 1 t o Y[ 0] */Y[ 1] = Y[ 0] * 2; / * ass i gn Y[ 0] * 2 expressi on t o Y[ 1] */Y[ 2] = Y[ 1] * 3; / * ass i gn Y[ 1] * 3 expressi on t o Y[ 2] */Y[ 3] = Y[ 2] * 4; / * ass i gn Y[ 2] * 4 expressi on t o Y[ 3] */Y[ 4] = Y[ 3] * 5; / * ass i gn Y[ 3] * 5 expressi on t o Y[ 4] */

  • 8/13/2019 Topic Arrays

    9/29

    TOPIC 1 ARRAYS 9

    Figure 1 5: Example of assignment statements that involve Y array elements

    Array indexes do not necessarily have to be constant values. We can also usei nt type expressions as an array index. However, the value of the index must bein the range of 0 and the value that is one less than the size of the array.

    Example:

    i nt a = 0;X[ a] = 5;

    In this example, x[ a] x[ 0] because a=0

    We can assign data from keyboard that data depend on the user key in. Theprogram code shows how to input data from keyboard. The program must useloop. Example input data are 34, 25, 26, 45 and 48.

  • 8/13/2019 Topic Arrays

    10/29

    TOPIC 1 ARRAYS10

    Program 1 1/ *Thi s pr ogr am was devel oped to i nput 5 i nt eger numbers and

    t he pr i nt t he t ot al . * /

    #i ncl ude voi d mai n( voi d){

    i nt x[ 5] , t ot al =0, i ;f or ( i = 0; i < 5; i ++) {

    pr i nt f ( "Ent er val ue f or x[ %d] = ", i ) ;scanf ( "%d", &( x[ i ] ) ) ;t ot al += x[ i ] ;

    }

    pr i nt f ( "Tot al = %d\ n", t ot al ) ;}

    Output:

    Think about the assignment given below. Look at the comments as aguide. Based on your understanding in the examples before this andthe illustration in Figure 1.5, draw an array based on the followingstatements:

    i nt S[ 5] ; / * decl ar e ar r ay wi t h 5 el ement s */i nt i = 0, j = 1;

    S[ i ] = 8; / * assi gn 8 t o S[ 0] */S[ j ] = S[ i ] + 5; / * assi gn S[ 0] +5 t o S[ 1] */S[ j +1] = S[ i ] * S[ j ] ; / * assi gn S[ 0] * S[ 1] t o S[ 2] */S[ j *3] = S[ i +2] ; / * assi gn S[ 2] t o S[ 3] */S[ j *4] = S[ j *2] ; / * assi gn S[ 2] t o S[ 4] */

    SELF-CHECK 1.3

  • 8/13/2019 Topic Arrays

    11/29

    TOPIC 1 ARRAYS 11

    In order to ensure that you understand what has been taught, answer thefollowing questions.

    1.2.4 Operations on Array Elements

    In C, we cannot implement an operation for the whole array. This means that, ifaand bare of the same arrays (having the same data type, size, and dimension),

    operations like assignment, comparison and the like should be performedelement by element.

    This is usually done by using the loop structure, where each loop will perform anoperation on a single array element. The number of loops is usually the same asthe number of elements in the array. Look at the following example. Theprogram code shows how to copy the contents of array A to array B.

    There are many operations that can be performed on array elements. Oneof the examples is the addition operation. Visit the websitehttp://www.phanderson.com/c/arraysum/html to see the techniquesthat are presented.

    ACTIVITY 1.5

    1. Referring to the arrays that are declared below, state the valuesthat are assigned to each following array element.

    (a) i nt abc[ 6] = {0, 2, 4, 6, 8, 10};(b) f l oat c[5] = {2. 0, 0. 5, 1. 2, 0. 3};(c) i nt xyz[ 10] = {5, 10, 0, 10, 5, 0, 0};

    2. Given the following program segments, what are the values of thearray elements at the end of the respective segments?

    (a) i nt M[ 5] = {2, 3}; (b) i nt R[ 4] , I = 1;M[ 2] = M[ 1] * 3; R[ i - 1] = 8;M[ 3] = M[ 2] * 1; R[ i ] = R[ i - 1] * 8;M[ 4] = M[ 0] * 2 * 3; R[ i +1] = R[ i ] + 10;

    R[ i +2] = R[ i ] * 5;

    SELF-CHECK 1.4

  • 8/13/2019 Topic Arrays

    12/29

    TOPIC 1 ARRAYS12

    Program 1 2/ * copy the cont ent s of ar r ay A t o ar r ay B */

    #i ncl ude #def i ne SI ZE 5

    voi d mai n( voi d) {i nt A[ SI ZE] = {2, 4, 6, 8, 10};i nt i ;i nt B[ SI ZE] ;

    / * copy one by one each arr ay el ement i n A t o ar r ay B */f or ( i = 0; i < SI ZE; i ++) {

    B[ i ] = A[ i ] ;

    }/ * pr i nt bot h ar r ays */f or ( i = 0; i < SI ZE; i ++) {

    pr i nt f ( A[ %d] = %d, B[ %d] = %d\ n, i , A[ i ] , i , B[ i ] ) ;}

    }

  • 8/13/2019 Topic Arrays

    13/29

    TOPIC 1 ARRAYS 13

    Reading two arrayelements.

    Using a loop to fill all of the elementsof the y[] array.

    Program 1 3#i ncl ude #def i ne N 10

    mai n( ){

    i nt a[ 2] ;f l oat [ N] ;

    a[0] = 11;a[1] = 22;

    b[ 3] = 777. 7;b[ 6] = 888. 8;

    pr i nt f ( a[ 0] = %3d, a[ 1] = %3d\ n, a[ 0] , a[ 1] ) ;pr i nt f ( b[ 3] = %8. 1f , b[ 6] = %8. 2f \ n, b[ 3] , b[ 6] ) ;

    }

    Program 1 4#i ncl udemai n( )

    { i nt a[ 4] = {11, 12}, b[ ] = {44, 55, 66}, i ;f l oat x[ 2] , y[ 4] ;

    pr i nt f ( Pl ease ent er t wo r eal number s\ n) ;scanf ( %f %f , &x[ 0 ] , &x[ 1] ) ;

    pr i nt f ( x[ 0] = %. 1f x[ 1] = %. 1f \ n\ n, x[ 0] , x[ 1] ) ;

    f or ( i =0; i

  • 8/13/2019 Topic Arrays

    14/29

    TOPIC 1 ARRAYS14

    Do the following exercise to help you in your understanding.

    Follow Program 1.2, 1.3 and 1.4. What are the output for the programs?

    SELF-CHECK 1.5

    1. Write a program that can read 5 integer values into an array andthen find the total for that array.

    2.

    What is the output for the following program:#i ncl ude

    voi d mai n( ) {

    i nt M[ 6] = {2, 5, 7, - 7, - 5, - 2};

    i nt N[6] , i ;

    N[ 0] = M[ 0] ;

    f or ( i = 1; i < 6; i ++)

    N[ i ] = M[ i ] + N[ i - 1] ;

    f or ( i = 0; i < 6; i ++)

    pr i nt f ( N[ %d] = %d\ n, i , N[ i ] ) ;

    }

    Answer:

    SELF-CHECK 1.6

  • 8/13/2019 Topic Arrays

    15/29

    TOPIC 1 ARRAYS 15

    1.2.5 Arrays and Functions

    In the previous Computer Programming Module, we discussed about functions.By using functions, our program code is more modular. We can also use thisconcept of arrays with functions.

    We can pass the entire array to a function as a parameter. The way that an arrayis passed to a function is quite different from the way other types of data arepassed. In order to pass an array element to a function, we need to state the arrayname only (without any bracket symbols or index numbers) as a functionparameter. In the definition of the function, the name of the array must bewritten in brackets, but without stating the size of the array.

    Look at the simple example.

    Program 1 5#i ncl ude voi d modi f yHour s( i nt [ ] , i nt ) ; / *f uncti on pr ot ot ype*/

    mai n( ){i nt Wor ki ngHour s[ 24] ;

    :modi f yHour s( Wor ki ngHour s, 24) ; / *f unct i on cal l */}

    / *f unct i on def i ni t i on*/voi d modi f yHour s( i nt b[ ] , i nt si ze){

    :}

    An individual element in an array can be passed call by value To pass an element of an array to a function, use the subscripted name of the

    array element as an argument in the function call

    Visit http://www.phanderson.com/c/arraysum.html again. Thistime, examine how functions are used with arrays. Modify all theprogram code if functions are not used. Will the answers still be thesame?

    ACTIVITY 1.4

  • 8/13/2019 Topic Arrays

    16/29

    TOPIC 1 ARRAYS16

    Look at the following example. We input 10 integer values and store them in anarray. Then, we would like to sort the contents of the array in an ascending order.The sorting operation is performed by the function numberSort ( ) . Then, we

    print the contents of the array.

    Program 1 6/ * Read 10 i nt eger val ues and sor t t he numbers usi ng number Sort ( )*/

    #i ncl ude

    voi d number Sor t ( i nt [ ] ) ; / * f unct i on pr ot ot ype */voi d mai n( voi d) {

    i nt number [ 10] ;

    i nt i ;

    f or ( i = 0; i < 10; i ++)scanf ( %d, &( number [ i ] ) ) ;

    number Sor t ( number ) ; / * f unct i on cal l */pr i nt f ( Val ues have been sor t ed\ n) ;f or ( i = 0; i < 10; i ++)

    pr i nt f ( %d, ( number [ i ] ) ) ;}

    voi d number Sor t ( i nt num[ ] ) { / * f unct i on def i ni t i on */

    i nt j , k, t empor ar y;

    f or ( j = 0; j < 10; j ++) {f or ( k = j +1; k < 10; k++) {

    i f ( num[ j ] > num[ k] ) {t empor ary = num[ j ] ;num[ j ] = num[ k] ;num[ k] = t emporar y;

    }}

    }

    } / * end of f unct i on */

    Look at the way we write the function prototype, function call, and the definitionof the function number Sor t ( ) .

    The output of the above program is given below.

  • 8/13/2019 Topic Arrays

    17/29

    TOPIC 1 ARRAYS 17

    1. Modify the solution to Question 1 in Self-Check1.4, but this time use afunction. Other than themai n() function, write three other functionsto solve the problem i.e a function to read values, a function to findthe total of element values, and a function to print values.

    2.

    Write a program that can read a group of data that represents dailytemperatures in an area in Kuala Lumpur for the month ofNovember 2001. Your program should produce the followingoutput:

    (a) The number of days that is hot (temperatures greater than85F), moderate (temperatures between 60 and 85F) and cold(temperatures less than 60F).

    (b) The average temperature for that month.(c) The number of days that have temperatures greater than the

    average.

    SELF-CHECK 1.7

  • 8/13/2019 Topic Arrays

    18/29

    TOPIC 1 ARRAYS18

    1.2.6 Case Study: Yearly Rainfall Summary

    Problem Statement

    You are given a table that shows the total distribution of monthly rainfall for2001 for an area in Kuala Lumpur.

    Month Jan Feb Mac Apr May June July Aug Sep Oct Nov Dec

    Total

    Rainfall190 195 268 307 235 144 105 193 215 223 235 208

    Based on the given information, you are required to write a program that canproduce the following summary:

    (a) Total yearly rainfall(b) Average rainfall for 2001(c) Wettest month(d) Driest monthData Design

    Input:rai nf al l Di str i but i on[ 12] : integer type array

    Output:t ot al Rai nf al l : Integer typeaver ageRai nf al l : Real typewet t est Mont h : Integer typedr i est Mont h : Integer type

    Solution DesignThe structural chart for this program is as follows in Figure 1.6.

  • 8/13/2019 Topic Arrays

    19/29

    TOPIC 1 ARRAYS 19

    Figure 1 6: Structural chart for the yearly rainfall summary problem

    ImplementationThe following is the program solution.

    Program 1 7/ * Year l y Rai nf al l Summar y Pr ogr am */#i ncl ude #def i ne N 12voi d r eadRai nDi str i but i on( i nt [ ] ) ;i nt cal cul at eTot al Rai n( i nt [ ] ) ;f l oat cal cul at eAver ageRai nf al l ( i nt ) ;

    i nt conf i r mWet t est Mont h( i nt [ ] ) ;i nt conf i r mDr i est Mont h( i nt [ ] ) ;voi d pr i nt Report ( i nt , f l oat , i nt , i nt ) ;

    voi d mai n( ) {i nt r ai n[ N] , t ot , max, wet , dr y;f l oat aver age;

    r eadRai nDi st r i but i on( r ai n) ;t ot = cal cul at eTot al Rai n( r ai n) ;aver age = cal cul at eAver ageRai nf al l ( t ot ) ;

    wet = conf i r mWet t est Mont h( r ai n) ;dr y = conf i r mDr i est Mont h( r ai n) ;

    pr i nt Repor t ( t ot , aver age, wet , dr y) ;}

  • 8/13/2019 Topic Arrays

    20/29

    TOPIC 1 ARRAYS20

    voi d r eadRai nDi st r i but i on( i nt r ai n[ ] ) {i nt i ;pr i nt f ( ent er t he t ot al mont hl y r ai nf al l di st r i but i on \ n);f or ( i = 0; i < N; i ++) {

    pr i nt f ( mont h %d : , i +1) ;scanf ( %d, &r ai n[ i ] ) ;

    }}i nt cal cul at eTot al Rai n( i nt r ai n[ ] ) {

    i nt i , t ot =0;f or ( i = 0; i < N; i ++) {

    t ot = t ot +r ai n[ i ] ;}r et ur n t ot ;

    }

    f l oat cal cul at eAver ageRai nf al l ( i nt t ot al ) {f l oat aver age;aver age = ( f l oat ) t ot al / N;r et ur n aver age;

    }i nt conf i r mWet t est Mont h( i nt r ai n[ ] ) {

    i nt i , max;max = 0;f or ( i = 1; i < N- 1; i ++) {

    i f ( r ai n[ i ] > r ai n[ max] ) {max = i ;

    }}

    r et urn max + 1;}

    i nt conf i r mDr i est Mont h( i nt r ai n[ ] ){

    i nt i , mi n;mi n=0;f or ( i = 1; i

  • 8/13/2019 Topic Arrays

    21/29

    TOPIC 1 ARRAYS 21

    case 6: pr i nt f ( J une) ; br eak;case 7: pr i nt f ( J ul y); br eak;case 8: pr i nt f ( August ) ; br eak;case 9: pr i nt f ( Sept ember ) ; br eak;case 10: pr i nt f ( Oct ober ) ; br eak;case 11: pr i nt f ( November ) ; br eak;case 12: pr i nt f ( December ) ; br eak;

    }pr i nt f ( \ n) ;}voi d pr i nt Repor t ( i nt t ot , f l oat ave, i nt wet , i nt dr y) {

    pr i nt f ( Tot al Rai nf al l %d\ n, t ot ) ;pr i nt f ( Aver age Rai nf al l %3. 2f \ n, ave) ;pr i nt f ( The wet t est Mont h i s) ;pr i ntMont hName(wet ) ;

    pr i nt f ( The dr i est Mont h i s);pr i nt Mont hName(dr y) ;

    }

    Output:

    TWO-DIMENSIONAL ARRAYSTwo-dimensional arrays can be regarded as a two-dimensional matrix that hasrows and columns.

    1.3

  • 8/13/2019 Topic Arrays

    22/29

    TOPIC 1 ARRAYS22

    1.3.1 Declaring Arrays and Initialising Array Elements

    The following is the declaration for a two-dimensional array:

    dat a_t ype ar r ay_name[number _of _r ow] [ number _of _col umn] ;

    where:

    data_type - type of data stored in the array array_name - name for the array number_of_row - a positive integer that represents the rows of the

    array

    number_of_column - a positive integer that represents the columns ofthe array

    The [ ] [ ] (brackets) identify the two dimensional array and the enclosednumbers indicate the number of rows and column.

    For example, the statement:

    i nt t abl e [ 3] [ 4] ;

    declares an integer type two-dimensional that consist of three rows and fourcolumns. The compiler creates the array table, which reserve memory space for

    twelve integer type elements.

    Let us assume that we would like to store a set of examination marks for 50students and each student has 10 examination scores. The data of the marks can

    be stored by using a two-dimensional array as follows:

    i nt mar ks[50] [ 10] ;

    With this declaration, the compiler will set aside 500 memory cells (which is 50 x10) as illustrated in Figure 1.7.

    Figure 1 7:Memory location illustration for the declaration of i nt mar ks[ 50] [ 10]

  • 8/13/2019 Topic Arrays

    23/29

    TOPIC 1 ARRAYS 23

    Each element can be referred to by using the name of the array as well as the rowindex and column index. For example, mar ks[ 1] [ 9] refers to the 10thexamination mark for the second student, as shown in Figure 1.7 above.

    The element contents of this two-dimensional array can be initially assignedduring the array declaration similar to how we would assign initial array elementvalues for one-dimensional arrays. For example, the following square array:

    i nt squar e[ 4] [ 4] ={ {1, 2, 3, 4}, {2, 3, 4, 5},{3, 4, 5, 6}, {4, 5, 6, 7}};

    The element contents of the square array can be illustrated as shown in thefollowing Figure 1.8:

    Figure 1 8:Memory cell content for the declared squarearray

    In order to ensure that you understand what has been taught, answer thefollowing questions.

    Array From the Twilight Zone in the websitehttp://home.twcny.rr.com/amanthoan/cweb/dimary.html. Look atthe example of two-dimensional array used.

    ACTIVITY 1.6

  • 8/13/2019 Topic Arrays

    24/29

    TOPIC 1 ARRAYS24

    1.3.2 Assigning and Accessing Array Elements

    In order to assign initial values or to access an array element in a two-dimensional array, we need to state to the name of the array along with the rowand column indexes. For this, we can use a nested loop as shown in the next

    example that reads 16 values to be stored in the squar e array.

    i nt squar e[ 4] [ 4] ;i nt i , j ;

    f or ( i = 0; i < 4; i ++) / * l oop i */f or ( j = 0; j < 4; J ++) / * l oop j */

    scanf ( %d, &( squar e[ i ] [ j ] ) ) ;

    In order to help you in your understanding, answer the following exercises.

    Try and predict the output if the above program segment ischanged in the following way:

    f or ( i = 0; i < 4; i ++) { / * l oop i */f or ( j = 0; j < 4; j ++) / * l oop j */

    } scanf ( %d, &( squar e[ i ] [ j ] ) ) ;

    SELF-CHECK 1.9

    Declare a two-dimensional array that has 3 rows and 5 columns called

    pqr.Assign the initial values for each row element of the first row withthe value 1, and each second row element with the value 2, and eachelement in the third row with the value 3.

    SELF-CHECK1.8

  • 8/13/2019 Topic Arrays

    25/29

    TOPIC 1 ARRAYS 25

    1.3.3 Arrays and Functions

    Passing two-dimensional arrays to a function is by referencing, which is the sameas passing a one-dimensional array to a function. Only the name of the arrayneed to be stated in the function invocation. Observe the following programsegment.

    #i ncl ude

    voi d r ead5Year Rai nf al l Di str i but i on( i nt r ai n[ ] [ 12] ) ;

    voi d mai n( ) {

    i nt rai n[ 5] [ 12] ;

    r ead5Year Rai nf al l Di st r i but i on( r ai n) ;. .

    }

    voi d r ead5Year Rai nf al l Di st r i but i on( i nt r ai n[ ] [ 12] ) {i nt i , j , yr ;

    f or ( i = 0; i < 5; i ++) {

    yr = 1997 + i ;pr i nt f ( ent er t ot al r ai n di str i but i on f or year %d\ n,

    y r ) ;

    f or ( j = 0; j < 12; j ++) {

    pr i nt f ( mont h %d : , j +1) ;

    scanf ( %d, &rai n[ i ] [ j ] ) ;

    }

    }

    }

    1. Regarding the arrays that are declared below, state the values thatare assigned to each following array element.

    (a) i nt p[ 2] [ 4] = {{2, 4, 6, 8}, {1, 3, 5, 7}};(b) i nt q[ 2] [ 4] = {{2, 4}, {1, 3}};

    2. Write a program segment that declares a two-dimensional arraywith 4 rows and 5 columns and assign each array element with thevalue -1 (Note: use loops for the assignment operation).

    SELF-CHECK 1.10

  • 8/13/2019 Topic Arrays

    26/29

    TOPIC 1 ARRAYS26

    1.3.4 Case Study: Two-dimensional Matrix Operations

    Problem StatementAssume that you would like to find the result of addition of two two-dimensional matrices where:

    c[ i ] [ j ] = a[ i ] [ j ] + b[ i ] [ j ]

    and then print the result that is produced.

    Data DesignInput: a[ ] [ ] , b[ ] [ ] : two-dimensional integer matrix

    Output:

    c [ ] [ ] : two-dimensional integer matrix that represents theadditionSolution Design

    The structural chart for this program is as shown in Figure 1.9:

    Figure 1 9: Structural chart for the two-dimensional matrix operation problem

  • 8/13/2019 Topic Arrays

    27/29

    TOPIC 1 ARRAYS 27

    ImplementationBelow is the solution program.

    Program 1 8/ * Two- di mensi onal Mat r i x Oper at i on Pr ogr am */#i ncl ude #def i ne MAXRow 10#def i ne MAXCol umn 10voi d r eadMat r i x( i nt x[ ] [ MAXCol umn] , i nt , i nt ) ;voi d cal cul at eAddi t i on( i nt a[ ] [ MAXCol umn] , i nt b[ ] [ MAXCol umn] ,i nt c[ ] [ MAXCol umn] , i nt , i nt ) ;voi d pr i nt Mat r i x( i nt x[ ] [ MAXCol umn] , i nt , i nt ) ;

    voi d mai n( ) {i nt r ow, col umn;i nt a [ MAXRow] [ MAXCol umn] , b [ MAXRow] [ MAXCol umn] ,

    c [ MAXRow] [ MAXCol umn] ;pr i nt f ( I nput number of r ows) ;scanf ( %d, &r ow) ;pr i nt f ( I nput number of col umns) ;scanf ( %d, &col umn) ;

    pr i nt f ( \ n\ nI nput Mat r i x A\ n);r eadMat r i x(a, r ow, col umn) ;pr i nt f ( \ n\ nI nput Mat r i x B\ n);r eadMat r i x(b, r ow, col umn) ;

    cal cul at eAddi t i on( a, b, c, r ow, col umn) ;

    pr i nt f ( Addi t i on of A and B i s\ n) ;pr i nt Mat r i x( c, r ow, col umn) ;

    }voi d r eadMat r i x( i nt x[ ] [ MAXCol umn] , i nt r ow, i nt col umn) {

    i nt i , j ;

    f or ( i = 0; i < r ow; i ++) {pr i nt f ( Ent er dat a f or r ow %d \ n, i +1) ;f or ( j = 0; j < col umn; j ++)

    scanf ( %d, &x[ i ] [ j ] ) ;}

    }voi d cal cul at eAddi t i on( i nt a[ ] [ MAXCol umn] , i nt b[ ] [ MAXCol umn] ,

    i nt c[ ] [ MAXCol umn] , i nt r ow, i nt col umn) {i nt i , j ;f or ( i = 0; i < r ow; i ++) {

  • 8/13/2019 Topic Arrays

    28/29

    TOPIC 1 ARRAYS28

    f or ( j = 0; j < col umn; j ++)c[ i ] [ j ] = a[ i ] [ j ] + b[ i ] [ j ] ;

    }}voi d pr i nt Mat r i x( i nt x[ ] [ MAXCol umn] , i nt r ow, i nt col umn) {

    i nt i , j ;

    f or ( i = 0; i < r ow; i ++) {f or ( j = 0; j < col umn; j ++)

    pr i nt f ( %4d, x[ i ] [ j ] ) ;

    pr i nt f ( \ n ) ;}

    }

    Sample output (only partial output is shown).

    An array is a data structure:

    (i) That consists of data items that are related

    (ii) That is of the same type

    (iii) That is of one or more dimension

    Also in this topic, methods for declaring, initialising values, sorting, andsearching one and two-dimensional array elements has been described.

  • 8/13/2019 Topic Arrays

    29/29

    TOPIC 1 ARRAYS 29

    Subsequent to this, the topic also discussed about the relationship betweenarrays and functions as well as the techniques for using them. Besides that,two case studies that related are to one or two-dimensional arrays are also

    provided for the students.

    One-dimensional Arrays Two-dimensional Arrays