Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module3 Notes

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 12

1

Module 3:
Module III - One and Two dimensional Arrays
3. To know and apply One and Two-dimensional Arrays
3.1 To know Arrays
3.2 To understand passing Array elements to a Function
3.3 To know Pointers and Arrays
3.4 To discuss Two-Dimensional Array
3.5 To know Pointers and Two – Dimensional Arrays
3.6 To know Array of Pointers

Array
Definition:

Array refers to a collection of same kind of data items.

Or

An array is a data structure that contains a group of elements. Typically these elements are all of
the same data type, such as an integer or string.

One dimensional array

Explanation:

To store total mark of a student in a class, we can use an integer variable,

int mark;

But if we need to store total mark of 50 students in a class, it is difficult to use 50 integer
variables. For this an integer array mark[50] is used.

Thus, ordinary variables are capable of holding only one value at a time. However, there are
situations in which we would want to store more than one value at a time in a single variable.
Arrays are used for this.

Array Declaration

The array is declared as

int mark[50];

 Here, int specifies the type of the array the word marks specifies the name of the array
variable.
 The [30] tells maximum number of elements of the type int can be stored in our array.
(maximum size of array).
Accessing Elements of an Array

1
2

 Once an array is declared, the individual elements in the array can be referred. This is
done with subscript, the number in the brackets following the array name.
 This number specifies the element’s position in the array. All the array elements are
numbered, starting with 0 and the last element is 1 less than the size of the array..

For eg, Individual mark can be represented by

mark[0], mark[1], mark[2], mark[3],……,mark[49]

 In program generally we are using the variable i as a subscript to refer to various


elements of the array.

Entering Data into an Array


Here is the section of code that places data into an array(for eg, marks of 30 students)

printf ( "\nEnter marks " ) ;


for ( i = 0 ; i <=30 ; i++ )
{
scanf ( "%d", &marks[i] ) ;
}

Reading Data from an Array


Suppose we want to find the average of marks of all students

for ( i = 0 ; i <= 29 ; i++ )


{
sum = sum + marks[i] ;
}
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;

Array Initialisation

An array can be initialized while declaring it. Following are a few examples that demonstrate
this.
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ;
Array Elements in Memory

Consider the following array initialization:


int arr[8] = {12, 34, 66, -45, 23, 346, 77, 90}

This arrangement of array elements in memory is shown in Figure


2
3

Whatever be the initial values, all the array elements would always be present in contiguous
memory locations.

………………………………………………………………………………………………….

Two dimensional array

Two Dimensional Array – also called matrix. A two dimensional array can be considered
as a collection of a number of one dimensional arrays

Initialising two dimensional arrays

Eg. Method 1

int stud[4][2]={

{ 1234, 56 }

{ 1212, 33 }

{ 1434, 80 }

{ 1312, 78 }

Method 2

Here is another method to initialise

int stud[4][2]= { 1234,56, 1212,33, 1434,80, 1312,78 };

Conceptually, the array arrangement can be shown as follows:

3
4

Fig:1.a

1234 is stored in stud[0][0], 56 is stored in stud[0][1] and so on.

 The above arrangement highlights the fact that a two- dimensional array is nothing but a
collection of a number of one- dimensional arrays placed one below the other.
 The arrangement of array elements in a two-dimensional array of students, which
contains roll nos. In one column and the marks in the other.
 The array arrangement shown in above figure 1.a is only conceptually true. This is
because memory doesn’t contain rows and columns.
 In memory whether it is a one-dimensional or a two-dimensional array the array elements
are stored in one continuous chain.
 The arrangement of array elements of a two-dimensional array in memory is shown
below:

We can easily refer to the marks obtained by the third student using the subscript notation as
shown below:

printf ( "Marks of third student = %d", stud[2][1] ) ;

program to create a square matrix of order m x n

main()
{
int mat[10][10], m,n,i,j;
printf(“enter the order of matrix m and n”);
scanf(“%d%d”,&m,&n);
printf(“enter the elements of matrix”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&mat[i][j]);
//display the matrix
printf(“the matrix you created is”);
for(i=0; i<m; i++)
4
5

{
for(j=0; j<n; j++)
{
printf(“%d ”, mat[i][j]);
}
printf(“\n”);
}
}

……………………………………………………………………………….

Char type array (Strings)

 A string consists of any no. of consecutive characters can be represented as a char type array.
The last character is always a null character (\0) which is placed automatically by the
compiler.

 (Strings-special kind of array consists of group of characters.)

 Character arrays or strings are used by programming languages to manipulate text such as
words and sentences.

Consider the charcter array,

char mess[10];

Suppose the message “hello” is to be stored into the array mess.

Now

mess[0]=‘h’

mess[1]=‘e’

...

...

mess[4]=‘o’

mess[5]=‘\0’

A string constant is a one-dimensional array of characters terminated by a null ( ‘\0’ ). For


example,
char mess[ ] = { 'H', 'E', 'L', 'L', 'O', '\0' } ; where ‘\0’ is called null character.
5
6

The terminating null (‘\0’) is important, because it is the only way the functions that work with a
string can know where the string ends. In fact, a string not terminated by a ‘\0’ is not really a
string, but merely a collection of characters.

Several char array definitions

Char message[]=“hello”;

Char message[6]=“hello”;

Char message[20]=“hello”; //extra array elts assigned zero or meaningless characters

Char message[5]; // it is not valid string since there is no place to store null character

Arrays and Strings

 A string can be represented by a one dimensional character array.


 So a list of strings can be store within a 2D character array. Each string will be stored in each row of
this 2d array.

Eg suppose we want to store a list of countries.

char countries[20][20];

……………………………………………………………………………………………

To understand passing Array elements to a Function

Array elements can be passed to a function in two ways. That is by calling the function

1. by value,
2. by reference.

6
7

 In the call by value we pass values of array elements to the function, whereas in the call by
reference we pass addresses of array elements to the function. These two calls are
illustrated below:

/* Demonstration of call by value */

main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
display ( marks[i] ) ; //function call with array elmt as arguement
}
display ( int m )
{
printf ( "%d ", m ) ;
}

And here’s the output...


55 65 75 56 78 78 90

 Here, we are passing an individual array element at a time to the function display( ) and
getting it printed in the function display( ).

Note that since at a time only one element is being passed(actual argument), this element is
copied in an ordinary integer variable m(formal argument), in the function display( ).

/* Demonstration of call by reference */

main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
disp ( &marks[i] ) ; //function call with address of elmt as argument
}

disp ( int *n )
{
printf ( "%d ", *n ) ;
}
And here’s the output... 55 65 75 56 78 78 90

 Here, we are passing addresses of individual array elements to the function display( ).
7
8

 Hence, the variable in which this address is collected (formal argument n) is declared
as a pointer variable.

And since n contains the address of array element, to print out the array element we are
using the ‘value at address’ operator (*). That is
printf ( "%d ", *n ) ;
………………………………………………………………………………………………..

Passing an Entire Array to a Function

 To pass an entire array to function, the array name must appear itself without brackets( or
subscripts) as actual argument within function call.
 When declaring formal argument, arrayname is written with a pair of empty square brackets.
Size need not be specified.

Eg. Average of an array

float average(int a, int x[]); //function prototype

main()
{
int n, list[50];
float avg;
………..
…………
avg=average(n,list) //function call with array name list as argument
}
float average( int a, int x[] ) //function definition
{
…………….
…………….
}
Note: When an array is passed to a function, the array name is interpreted as the address of
the first array element (address of mem. Location containing first array element). This
address is assigned to corresponding formal argument and therefore formal argument
becomes pointer to first array element.

8
9

……………………………………………………………………………………

Pointers and one Dimensional arrays

 X is a one dimensional array, the address of the first element can be expressed as either
&x[0] or simply x.
 the address of the second element can be expressed as either &x[1] or simply x+1 and so
on.
 General the address of the (i+1)th element can be expressed as either &x[i] or simply x+i)

since &x[i] or (x+i ) both represent the addresss of ith element, x[i] and *(x+i) both
represent the content of that address. That is the value of ith element of x

------------------------------------------------------------------------------------------------------

Pointers and 2 Dimensional arrays – pointer to array

The very important fact is that a two dimensional array can be considered as a collection of
a number of one dimensional arrays

Suppose x is a 2D array having 10 rows and 20 cols. We can declare x as

int (*x)[20];

In this, x is defined to be a pointer two a group of contiguous, one dimensional, 20


element integer array.

Thus x points to first 20 element array. (which is actually the first row of original 2D array)

Similarly (x + 1) points to second 20-elt array.(which is actually the second row ) and so on.

9
10

Method of accessing an individual array element x[2][3]

( x + 2 ) is a pointer to row 2.

Therefore *( x + 2 ) is a pointer to first element in row 2.

Adding 3 to this, we get *(x + 2 ) + 3, which is a pointer to 3rd column in this row

Therefore *( *(x + 2 ) + 3 ) refers to the item in 3rd column of 2nd row.

So x[2][3] is equivalent to *( *(x + 2 ) + 3 )

Program to create and display a 2D array . Use functions which accepts a pointer to
array as argument

read( int (*x)[20]);


display(int (*x)[20]);
main()
{
int a[10][20];
read(a); /* read the elements*/
display(a); /* display the elements*/
}
read( int (*x)[20]) // x is a pointer to a group of one dimensional 20 elt int arrays.
{
int row, col;
printf(“enter the data”);
for(row=0;row<3;row++)
for(col=0;col<3;col++)
10
11

scanf(“%d”, (*(a+row)+col) ); //equilant to &a[row][col]


}
display(int (*x)[20])
{ printf(“The matrix is”);
for(row=0;row<3;row++)
{ for(col=0;col<3;col++)
printf(“%d ”, *(*(a+row)+col) ); //equilant to a[row][col]
printf(“\n”);
}

------------------------------------------------------------------------------------------------

Pointers and 2 Dimensional arrays - array of pointers

 A two dimensional array can be also expressed in terms of array of pointers rather than a
pointer to a group of contiguous arrays (which we discussed earlier)
 Each pointer will indicate the beginning of a separate 1 dimensional array.
 In general terms, a 2 D array can be defined as a 1D array of pointers by writing

datatype * array[exp1];

Rather than the conventional array definition, datatype array[exp1][exp2];

Eg.

int x[10][20]; is a 2D array with 10 rows and 20 columns.

we can define x as a 1D array of pointers by writing

int *x[10];

11
12

Method of accessing an individual array element x[2][3]

x[2] is a pointer to the first element in row 2. So ( x[2] + 3 ) points to col 3 in row 3

Therefore, *( x[2] + 3) refers the content at row 2 & col3

That is x[2][3] is equivalent to *( x[2] + 3)

12

You might also like