You are on page 1of 29

Topic

Arrays

LEARNING OUTCOMES
By the end of this topic, you should be able to: 1. Declare and perform manipulations on one-dimensional arrays and two-dimensional arrays; 2. Solve programming problems using one-dimensional arrays and two-dimensional arrays; and 3. Solve programming problems using arrays that involve functions.

INTRODUCTION
A computer is a machine that manipulates information. The study of Information Technology/Computer Science therefore, inevitably, includes the study of how information is organised in a computer, how it can be manipulated and how it can be utilised. Thus, it is exceedingly important to understand the concept of information organisation and manipulation. A computer is referred to as a data processing machine using which raw data is processed to get it transformed into refined data, and this transformation is done through algorithms. Therefore, we can say that raw data is input and algorithms are 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. The algorithms that we can use to process the data depend on the structure used for the representation of data. Therefore, it becomes necessary to study the various structures for the representation of data and the algorithms that operate on these structures. Knowing the structures, one can think of the various alternative representations of the data and the corresponding operations operating on them and choose the one that is better suited to the requirement.

TOPIC 1 ARRAYS

The study of different structures for representation of data and the algorithms that operate on these structures constitute what we call study of data structures. A "data structure" which displays the relationship of adjacency between elements is said to be "linear". This type of data structure is used to represent one of the simplest 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 it can 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) (b) (c) (d) (e) (f) Find the length of the list, n; Read the list from left to right or (right to left); Retrieve the ith element of the list, 1 n; Store a new value into the ith position, 1 n; 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 Delete the element at position i, 1in causing elements numbered i+1,...n to become numbered i, i+1,....n-1.

The simplest linear data structure that makes use of computed addresses to locate its elements is the one dimensional array. This topic will discuss the concept of arrays, one-dimensional arrays and twodimensional arrays, and how to use them in programming. Therefore, are you ready? If so, then let us proceed to explore all that is related to arrays.

TOPIC 1 ARRAYS

1.1

CONCEPT OF ARRAY

Do you still remember variables? Can you compare the concept of variables and arrays? Arrays are data structures that contain data items of the same type. Arrays also contain static data. This means that the size of the array is fixed from the declaration all the way to the final program implementation.

Why do we need arrays in our programming? This question can be answered by giving an example. Let us say that you would like to keep a record of your personal spending for the year 2002. You can file all your receipts and details of expenditure in multiple files according to the month. This means that you have 12 different files. However, would not it be easier if you could manage a single file with 12 compartments? Let us relate this scenario to computer programming. Let us just say that we would like to write a program to manage your expenses. Your program can declare 12 separate variables to represent the total monthly expenditure (just like how we would use 12 files to store the receipts). However, we could further improve our program by using an array that has 12 elements, that is, by storing the monthly total spending in each of the array elements.

1.2

ONE-DIMENSIONAL ARRAYS

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

1.2.1

Declaring Arrays

It is easy to declare an array. We can use the same method that we use to declare normal variables, but the difference lies in that the name of the array must include the array size specification (which is enclosed by the [ and ] symbols). In general, we can declare one-dimensional arrays as follows:
data_type array_name[number_of_elements];

TOPIC 1 ARRAYS

which: data_type array_name number_of_elements type of data that will be stored in the array the name of the array a positive integer that indicates how many elements should be stored in memory

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

The above statement will declare an array that is called number and is of size 10. This declaration will instruct the compiler to reserve 10 memory spaces in sequence that can be referred as number. This sequence of memory spaces is also known as array elements. Since the data_type for number is declared as being the int type, therefore, the number array elements can contain data of int type only. Observe the illustration in Figure 1.1.

Figure 1.1: Illustration of memory location for the declaration of int number[10]

The value within the [ ] brackets is also known as the array index. The array index always begins with 0 and ends with the size of the array subtracted by 1. In the 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 consists of an expression and the expression is evaluated to determine the index. If a

TOPIC 1 ARRAYS

program uses an expression as an index, then the expression is evaluated to determine 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 of type char can be used to store a character string.

ACTIVITY 1.1
Draw a memory location as reference for each element of the arrays that are declared as follows:
char text[80]; int marks[100]; float high[5]; /*character array of size 80*/ /*integer array of size 100*/ /*real number array of size 5*/

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

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

SELF-CHECK 1.1
Declare a suitable array for each of the following: (a) (b) An array for 30 real numbers An array for a sequence of 126 characters

TOPIC 1 ARRAYS

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.
int digit[10] = {7, 5, 3, 8, 0, 9, 2, 4, 1, 6};

Array with Initial Values

Figure 1.2: Array initialisation and memory location illustration

All the array elements that are not given initial values will be set with the value of 0 automatically. See the following example:
int digit1[10] = {1, 2, 3};

The result is the digit1 array will have the following sequential values: Array without Full Initial Values

Figure 1.3: Partial initialisation of elements and memory location illustration

Another 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 array declaration. Here, the size of the digit2 array is 5, based on the number of elements in the initial value list. int digit2[] = { 1, 2, 3, 4,5 } ;

TOPIC 1 ARRAYS

ACTIVITY 1.2
Draw a diagram that illustrates the memory location for the declaration of the digit2 array. In order to ensure that you understand what has been taught, answer the following questions.

SELF-CHECK 1.2
Write a suitable array declaration for each of the following: (a) (b) Declare a one-dimensional integer array of size 12 that is called odd. Assign the values 1, 3, 5, 6, ..., 23 to the elements of that array. Declare a one-dimensional real number array of size 6 that is called constant. Assign the following values to the array elements: 0.02, -0.45, 5.77, -2.55, 7.50, -5

1.2.3

Assigning and Accessing Array Elements

We have looked at the array index that enables us to differentiate every element in 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:
int digit[10] = {7, 5, 3, 8, 0, 9, 2, 4, 1, 6}

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

Figure 1.4: Memory element of digit array

TOPIC 1 ARRAYS

We can assign any data values for each of the array element that has been defined by using the assignment statement. However, the value that is assigned must 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 digit array without initial values. Each following assignment statement assigns values to the array element. As a result we will have an array that is the same array as in Figure 1.4.
int month[10]; month[0] = 7; month[1] = 5; month[2] = 3; /* /* /* /* declare month array of size 10 */ assign 7 to the first element */ assign 5 to the second element */ assign 3 to the third element */

Can you note down the values that are assigned based on
int month[10] = {7, 5, 3, 8, 0, 9, 2, 4, 1, 6}; month[3] = ? month[4] = ? : month[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 the assignment statement for the array element can also be an expression. Look at the following example:
int X[3]; X[0] = 2; X[1] = 3 + 4; X[2] = 5 * 6; /* /* /* /* array declaration of 3 elements */ assign 2 to X[0] */ assign (3 + 4)expression to X[1] */ assign (5 *6) expression to 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 are assigned in these assignment statements are explained in Figure 1.5.
int Y[5]; Y[0] = 1; Y[1] = Y[0] Y[2] = Y[1] Y[3] = Y[2] Y[4] = Y[3] /* /* /* /* /* /* array declaration of 5 elements */ assign 1 to Y[0] */ assign Y[0] * 2 expression to Y[1] assign Y[1] * 3 expression to Y[2] assign Y[2] * 4 expression to Y[3] assign Y[3] * 5 expression to Y[4]

* * * *

2; 3; 4; 5;

*/ */ */ */

TOPIC 1 ARRAYS

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 use int type expressions as an array index. However, the value of the index must be in the range of 0 and the value that is one less than the size of the array. Example:
int 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. The program code shows how to input data from keyboard. The program must use loop. Example input data are 34, 25, 26, 45 and 48.

10

TOPIC 1 ARRAYS

Program 1.1 /*This program was developed to input 5 integer numbers and the print the total. */ #include <stdio.h> void main(void) { int x[5], total=0, i; for(i = 0; i < 5; i++){ printf("Enter value for x[%d] = ", i); scanf("%d", &(x[i])); total += x[i]; } printf("Total = %d\n", total); } Output:

SELF-CHECK 1.3
Think about the assignment given below. Look at the comments as a guide. Based on your understanding in the examples before this and the illustration in Figure 1.5, draw an array based on the following statements:
int S[5]; int i = 0, j = 1; S[i] = S[j] = S[j+1] S[j*3] S[j*4] 8; S[i] + 5; = S[i] * S[j]; = S[i+2]; = S[j*2]; /* declare array with 5 elements */

/* /* /* /* /*

assign assign assign assign assign

8 to S[0] */ S[0]+5 to S[1] */ S[0]* S[1] to S[2]*/ S[2] to S[3]*/ S[2] to S[4]*/

TOPIC 1 ARRAYS

11

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

SELF-CHECK 1.4
1. Referring to the arrays that are declared below, state the values that are assigned to each following array element. (a) (b) (c) 2.
int abc[6] = {0, 2, 4, 6, 8, 10}; float c[5] = {2.0, 0.5, 1.2, 0.3}; int xyz[10]= {5, 10, 0, 10, 5, 0, 0};

Given the following program segments, what are the values of the array elements at the end of the respective segments? (a)
int M[5] = {2, 3}; M[2] = M[1] * 3; M[3] = M[2] * 1; M[4] = M[0] * 2 * 3;

(b)

int R[4], I = R[i-1] = 8; R[i] = R[i-1] R[i+1] = R[i] R[i+2] = R[i]

1; * 8; + 10; * 5;

1.2.4

Operations on Array Elements


ACTIVITY 1.5

There are many operations that can be performed on array elements. One of the examples is the addition operation. Visit the website http://www.phanderson.com/c/arraysum/html to see the techniques that are presented.

In C, we cannot implement an operation for the whole array. This means that, if a and b are of the same arrays (having the same data type, size, and dimension), operations like assignment, comparison and the like should be performed element by element. This is usually done by using the loop structure, where each loop will perform an operation on a single array element. The number of loops is usually the same as the number of elements in the array. Look at the following example. The program code shows how to copy the contents of array A to array B.

12

TOPIC 1 ARRAYS

Program 1.2
/* copy the contents of array A to array B */ #include <stdio.h> #define SIZE 5 void main(void) { int A[SIZE] = {2, 4, 6, 8, 10}; int i; int B[SIZE]; /* copy one by one each array element in A to array B */ for (i = 0; i < SIZE; i++) { B[i] = A[i]; } /* print both arrays */ for (i = 0; i < SIZE; i++) { printf(A[%d] = %d, B[%d] = %d\n, i, A[i], i, B[i]); } }

TOPIC 1 ARRAYS

13

Program 1.3 #include <stdio.h> #define N 10 main() { int a[2]; float [N]; a[0] = 11; a[1] = 22; b[3] = 777.7; b[6] = 888.8;
These statements fill all of the elements of the a[] array. Using a constant to size arrays is good programming practice.

Arrays declarations. The value enclosed in brackets indicates the total number of array elements for which space is to be reserved.

printf(a[0] = %3d, a[1] = %3d\n, a[0], a[1]); printf(b[3] = %8.1f, b[6] = %8.2f \n, b[3], b[6]); }
This initialise the first two elements of the a[] array. All other elements are then automatically set to zero. Because no array size is given (the brackets are empty) and three values are given in braces, the array is automatically declared to have a size of three with the values shown being the initial element values.

Program 1.4 #include <stdio.h> main()

int a[4] = {11, 12}, float x[2], y[4];

b[ ] = {44, 55, 66}, i;


Reading two array elements.

printf(Please enter two real numbers\n); scanf(%f %f, &x[ 0 ], &x[1]); printf(x[0] = %.1f

x[1] = %.1f\n\n, x[0], x[1]);

Using a loop to fill all of the elements for (i=0; i<4; i++) of the y[] array. { y[ i ] = (a[i]+ b[2])* 10.0; printf(y[%1d] = %.2f\n, i, y[i]); }

return 0; }

14

TOPIC 1 ARRAYS

SELF-CHECK 1.5
Follow Program 1.2, 1.3 and 1.4. What are the output for the programs?

Do the following exercise to help you in your understanding.

SELF-CHECK 1.6
1. 2. Write a program that can read 5 integer values into an array and then find the total for that array. What is the output for the following program:
#include <stdio.h> void main() { int M[6] = {2, 5, 7, -7, -5, -2}; int N[6], i; N[0] = M[0]; for (i = 1; i < 6; i++) N[i] = M[i] + N[i-1]; for (i = 0; i < 6; i++) printf(N[%d] = %d\n, i, N[i]);

}
Answer:

TOPIC 1 ARRAYS

15

1.2.5

Arrays and Functions

ACTIVITY 1.4
Visit http://www.phanderson.com/c/arraysum.html again. This time, examine how functions are used with arrays. Modify all the program code if functions are not used. Will the answers still be the same?

In the previous Computer Programming Module, we discussed about functions. By using functions, our program code is more modular. We can also use this concept of arrays with functions. We can pass the entire array to a function as a parameter. The way that an array is passed to a function is quite different from the way other types of data are passed. In order to pass an array element to a function, we need to state the array name only (without any bracket symbols or index numbers) as a function parameter. In the definition of the function, the name of the array must be written in brackets, but without stating the size of the array. Look at the simple example. Program 1.5
#include <stdio.h> void modifyHours(int [], int); /*function prototype*/ main() { int WorkingHours[24]; : modifyHours(WorkingHours, 24);/*function call*/ } /*function definition*/ void modifyHours(int b[], int size) { : }

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

16

TOPIC 1 ARRAYS

Look at the following example. We input 10 integer values and store them in an array. 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 integer values and sort the numbers using numberSort() */ #include <stdio.h> void numberSort (int []); void main(void) { int number[10]; int i; /* function prototype */

for (i = 0; i < 10; i++) scanf(%d, &(number[i])); numberSort(number); /* function call */ printf(Values have been sorted\n); for (i = 0; i < 10; i++) printf(%d, (number[i])); } void numberSort(int num[]) { int j, k, temporary; /* function definition */

for (j = 0; j < 10; j++) { for (k = j+1; k < 10; k++) { if (num[j] > num[k]) { temporary = num[j]; num[j] = num[k]; num[k] = temporary; } } } /* end of function */

Look at the way we write the function prototype, function call, and the definition of the function numberSort(). The output of the above program is given below.

TOPIC 1 ARRAYS

17

SELF-CHECK 1.7
1. Modify the solution to Question 1 in Self-Check1.4, but this time use a function. Other than the main() function, write three other functions to solve the problem i.e a function to read values, a function to find the total of element values, and a function to print values. Write a program that can read a group of data that represents daily temperatures in an area in Kuala Lumpur for the month of November 2001. Your program should produce the following output: (a) The number of days that is hot (temperatures greater than 85F), moderate (temperatures between 60 and 85F) and cold (temperatures less than 60F). The average temperature for that month. The number of days that have temperatures greater than the average.

2.

(b) (c)

18

TOPIC 1 ARRAYS

1.2.6

Case Study: Yearly Rainfall Summary

Problem Statement You are given a table that shows the total distribution of monthly rainfall for 2001 for an area in Kuala Lumpur.
Month Total Rainfall Jan 190 Feb 195 Mac 268 Apr 307 May 235 June 144 July 105 Aug 193 Sep 215 Oct 223 Nov 235 Dec 208

Based on the given information, you are required to write a program that can produce the following summary: (a) (b) (c) (d) Total yearly rainfall Average rainfall for 2001 Wettest month Driest month

Data Design Input:


rainfallDistribution[12] : integer type array

Output:
totalRainfall averageRainfall wettestMonth driestMonth

: Integer type : Real type : Integer type : Integer type

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

TOPIC 1 ARRAYS

19

Figure 1.6: Structural chart for the yearly rainfall summary problem

Implementation The following is the program solution. Program 1.7


/* Yearly Rainfall Summary Program */ #include <stdio.h> #define N 12 void readRainDistribution(int []); int calculateTotalRain(int []); float calculateAverageRainfall(int); int confirmWettestMonth(int []); int confirmDriestMonth(int []); void printReport(int, float, int, int); void main() { int rain[N], tot, max, wet, dry; float average; readRainDistribution(rain); tot = calculateTotalRain(rain); average = calculateAverageRainfall(tot); wet = confirmWettestMonth(rain); dry = confirmDriestMonth(rain);

printReport(tot, average, wet, dry); }

20

TOPIC 1 ARRAYS

void readRainDistribution(int rain[]) { int i; printf(enter the total monthly rainfall distribution \n); for (i = 0; i < N; i++) { printf(month %d : , i+1); scanf(%d, &rain[i]); } } int calculateTotalRain(int rain[]) { int i, tot=0; for (i = 0; i < N; i++) { tot = tot +rain[i]; } return tot; } float calculateAverageRainfall(int total) { float average; average = (float) total / N; return average; } int confirmWettestMonth(int rain[]) { int i, max; max = 0; for (i = 1; i < N-1; i++) { if (rain[i] > rain[max]) { max = i; } } return max + 1; } int confirmDriestMonth(int rain[]) { int i, min; min=0; for (i = 1; i <= N; i++) { if (rain[i] < rain[min]) min = i;} return min + 1; } void printMonthName(int i) { switch (i) { case 1: printf(January); break; case 2: printf(February); break; case 3: printf(March); break; case 4: printf(April); break; case 5: printf(May); break;

TOPIC 1 ARRAYS

21

case case case case case case case

6: 7: 8: 9: 10: 11: 12:

printf(June); break; printf(July); break; printf(August); break; printf(September); break; printf(October); break; printf(November); break; printf(December); break;

} printf(\n); } void printReport(int tot, float ave, int wet, int dry) { printf (Total Rainfall %d\n, tot); printf (Average Rainfall %3.2f\n, ave); printf (The wettest Month is); printMonthName(wet); printf (The driest Month is); printMonthName(dry);

} Output:

1.3

TWO-DIMENSIONAL ARRAYS

Two-dimensional arrays can be regarded as a two-dimensional matrix that has rows and columns.

22

TOPIC 1 ARRAYS

1.3.1

Declaring Arrays and Initialising Array Elements

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


data_type array_name[number_of_row][number_of_column];

where:

data_type array_name number_of_row number_of_column

type of data stored in the array name for the array a positive integer that represents the rows of the array a positive integer that represents the columns of the array

The [ ] [ ] (brackets) identify the two dimensional array and the enclosed numbers indicate the number of rows and column. For example, the statement:
int table [3] [4];

declares an integer type two-dimensional that consist of three rows and four columns. 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 50 students and each student has 10 examination scores. The data of the marks can be stored by using a two-dimensional array as follows:
int marks[50][10];

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

Figure 1.7: Memory location illustration for the declaration of int marks[50][10]

TOPIC 1 ARRAYS

23

Each element can be referred to by using the name of the array as well as the row index and column index. For example, marks[1][9] refers to the 10th examination mark for the second student, as shown in Figure 1.7 above. The element contents of this two-dimensional array can be initially assigned during the array declaration similar to how we would assign initial array element values for one-dimensional arrays. For example, the following square array:
int square[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 the following Figure 1.8:

Figure 1.8: Memory cell content for the declared square array

ACTIVITY 1.6
Array From the Twilight Zone in the website http://home.twcny.rr.com/amanthoan/cweb/dimary.html. Look at the example of two-dimensional array used.

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

24

TOPIC 1 ARRAYS

SELF-CHECK1.8
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 with the value 1, and each second row element with the value 2, and each element in the third row with the value 3.

1.3.2

Assigning and Accessing Array Elements

In order to assign initial values or to access an array element in a twodimensional array, we need to state to the name of the array along with the row and 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 square array.
int square[4][4]; int i,j; for (i = 0; i < 4; i++) /* loop i */ for (j = 0; j < 4; J++) /* loop j */ scanf(%d, &(square[i][j]));

SELF-CHECK 1.9
Try and predict the output if the above program segment is changed in the following way:
for(i = 0; i < 4; i++) { /* loop i */ for(j = 0; j < 4; j++) /* loop j */ } scanf(%d, &(square[i][j]));

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

TOPIC 1 ARRAYS

25

SELF-CHECK 1.10
1. Regarding the arrays that are declared below, state the values that are assigned to each following array element. (a) int p[2][4] = {{2, 4, 6, 8}, {1, 3, 5, 7}}; (b) int q[2][4] = {{2, 4}, {1, 3}}; 2. Write a program segment that declares a two-dimensional array with 4 rows and 5 columns and assign each array element with the value -1 (Note: use loops for the assignment operation).

1.3.3

Arrays and Functions

Passing two-dimensional arrays to a function is by referencing, which is the same as passing a one-dimensional array to a function. Only the name of the array need to be stated in the function invocation. Observe the following program segment.
#include <stdio.h> void read5YearRainfallDistribution(int rain[][12]); void main(){ int rain[5][12]; read5YearRainfallDistribution(rain); .. } void read5YearRainfallDistribution(int rain[][12]) { int i, j, yr; for (i = 0; i < 5; i++) { yr = 1997 + i; printf(enter total rain distribution for year %d\n, yr); for (j = 0; j < 12; j++) { printf(month %d :, j+1); scanf(%d, &rain[i][j]); } } }

26

TOPIC 1 ARRAYS

1.3.4

Case Study: Two-dimensional Matrix Operations

Problem Statement Assume that you would like to find the result of addition of two twodimensional matrices where:
c[i][j] = a[i][j] + b[i][j]

and then print the result that is produced. Data Design Input:
a[][], b[][]

: two-dimensional integer matrix

Output:
c[][]

: two-dimensional integer matrix that represents the addition

Solution 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

TOPIC 1 ARRAYS

27

Implementation Below is the solution program. Program 1.8


/* Two-dimensional Matrix Operation Program */ #include <stdio.h> #define MAXRow 10 #define MAXColumn 10 void readMatrix(int x[] [MAXColumn], int, int); void calculateAddition(int a[] [MAXColumn], int b[][MAXColumn], int c[][MAXColumn], int, int); void printMatrix(int x[][MAXColumn], int, int); void main() { int row, column; int a [MAXRow] [MAXColumn], b [MAXRow] [MAXColumn], c [MAXRow] [MAXColumn]; printf(Input number of rows); scanf(%d, &row); printf(Input number of columns); scanf(%d, &column); printf(\n\nInput Matrix A\n); readMatrix(a, row, column); printf(\n\nInput Matrix B\n); readMatrix(b, row, column); calculateAddition(a, b, c, row, column); printf(Addition of A and B is\n); printMatrix(c, row, column); } void readMatrix(int x[][MAXColumn], int row, int column){ int i,j; for (i = 0; i < row; i++) { printf (Enter data for row %d \n, i+1); for (j = 0; j < column; j++) scanf(%d, &x[i][j]); } } void calculateAddition(int a[][MAXColumn], int b[][MAXColumn], int c[][MAXColumn], int row, int column) { int i,j; for (i = 0; i < row; i++) {

28

TOPIC 1 ARRAYS

for (j = 0; j < column; j++) c[i][j] = a[i][j] + b[i][j]; } } void printMatrix(int x[][MAXColumn], int row, int column) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < column; j++) printf(%4d, x[i][j]); printf(\n); } }

Sample output (only partial output is shown).

An array is a data structure: (i) (ii) That consists of data items that are related That is of the same type

(iii) That is of one or more dimension Also in this topic, methods for declaring, initialising values, sorting, and searching one and two-dimensional array elements has been described.

TOPIC 1 ARRAYS

29

Subsequent to this, the topic also discussed about the relationship between arrays 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

You might also like