• No results found

Arrays.pdf

N/A
N/A
Protected

Academic year: 2020

Share "Arrays.pdf"

Copied!
17
0
0

Loading.... (view fulltext now)

Full text

(1)

What is an Array?

• An array is collection of variables of a certain type,

placed contiguously (alongside) in memory.

• An array is simply a number of memory locations, each

of which can store the same data type and which can be

referenced through the same variable name.

• An array is a collective name given to a group of

similar quantities & the similar quantities could be

marks of 100 students, or salaries of 300 employee or

ages of 50 employees.

• These similar elements could be all integers, or all

floats or all characters etc.

Declaration of an Array

• Standard array declaration is as follows:

type var_name[size];

• For example:

int temp[7];

Here the int specifies the type of variable, and temp is

the name of array.

[7] tells how many variables of type int

will be in the

array.

Each separate variable in array is called an “element”

More Examples:

(2)

Arrays in Memory

• In C Language, arrays starts at position 0.

• The elements of the array occupy adjacent locations

in memory

• Example: int temp[10];

• The k-th element of array A is specified by A[k-1]

(0 based)

Subscripts:

the numbers in brackets following the

array name are called subscript and are used to refer to

individual elements of array.

0 1 2 3 4 5 6 7 8 9

int temp[10]

10 elements

• This number has a different meaning when referring

to an array element than it does when defining array;

when the number in brackets is size of array.

• When referring to an array element, this number

specifies the element’s position in array

• All array elements are numbered, starting at 0, the

element of array with number 2 would be referred as:

temp[2]

• This is not the second element but the third, as

numbering starts from 0, thus the last array element

is one less than the size of array.

0 1 2 3 4 5 6 7 8 9

temp[2]

(3)

Using Arrays

int a[5], i;

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

{

a[i] = i;

}

int a[5];

a[0] = 2;

a[1] = 4;

a[2] = 6;

a[3] = 8;

a[4] = 10;

2 4 6 8 10

a[0] a[1] a[2] a[3] a[4]

0 1 2 3 4

a[0] a[1] a[2] a[3] a[4]

• Suppose you wanted to find the average temperature for a particular week.

void main ( void ) {

int temper [ 7 ] ; /*array definition*/ int day , sum ;

for ( day = 0; day < 7; day ++ )

{ printf (“Enter Temperature for day %d : “, day ) ; scanf ( “ %d “, &temper [ day ] ) ;

}

sum = 0 ;

for ( day = 0; day < 7; day ++ ) sum + = temper [ day ] ;

(4)

• The program reads in 7 temperatures, stores them in

an array and then to calculate average temperature,

reads them back out of the array, adding them

together, dividing by 7.

Output:

Enter temperature for day0: 74

Enter temperature for day1: 76

Enter temperature for day2: 77

Enter temperature for day3: 77

Enter temperature for day4: 64

Enter temperature for day5: 66

Enter temperature for day6: 69

Average is 71.

• Entering data into Array:

– For loop causes the process of asking for and receiving a temperature from the user to be repeated 7 times.

for ( day = 0; day < 7; day ++ )

{ printf (“Enter Temperature for day %d : “, day ) ; scanf ( “ %d “, &temper [ day ] ) ;

}

• Entering data into Array:

– For loop is much the same, but now the body of loop causes each day’s temperature to be added to a running total sum. When all of them are added up, the result is divided by 7

sum = 0 ;

(5)

Using Different Variable Type

void main (void) {

float temper [ 7 ] , sum; int day ;

for ( day = 0 ; day < 7 ; day + + ) {

printf ( “Enter Temperature for day %d: “, day ) ; scanf ( “ %f “, &temper [ day ] ) ;

}

sum = 0.0 ;

for ( day = 0; day < 7; day ++ ) sum + = temper [ day ] ;

printf ( “ Average is %.1f “, sum / 7.0 ); }

Reading in an Unknown Number of Elements

void main (void)

{ float temper [ 40 ] , sum = 0.0; int num , day = 0;

do {

printf (“Enter Temperature for day %d: “, day ) ; scanf (“ %f “, &temper [ day ] ) ;

}

while ( temper [ day + + ] > 0 ) ;

num = day - 1 ; /* no of temps entered */

for ( day = 0 ; day < num ; day + + ) sum + = temper [ day ] ;

(6)

• For loop is replaced with a do while loop, which

repeatedly asks the user to enter a temperature and store

the responses in the array temper,

until a temperature

of zero or less is entered.

• When the last item has been typed, the variable day will

have reached a value 1 greater than the total number of

items entered because it counts 0 (or –ve number)

which the user entered to terminate the input.

• Thus to find the number of items entered, num

we

subtract 1 from day.

num is then used as limit in the second for loop, which

adds up temperatures, and its also used as divisor of the

resulting sum.

Bound Checking

• In the previous program we have made the size of the

array to be 40. But a user decided to enter 2 months

worth of data? As it turns out, there probably would be

big trouble. How?

• In C there is no check to see if the subscript used for an

array will exceed the size of array.

• Data entered with too large a subscript will simply be

placed in memory outside the array, this will lead to

unpredictable results.

(7)

Bound Checking

Solution:

– If there is the slightest possibility that the user might

enter too many items, we have to check for this

possibility.

• Now if the loop is entered with day = 40, which is 1

past the end of buffer at 39, the message “Buffer full”

is printed, and break statement takes us out of the loop

and enters the second part of the program.

day is incremented since the while statement won’t be

executed.

Bound Checking

do

{

if ( day > = 40 ) /* beyond array end*/ {

printf ( “ Buffer Size Full “ ) ; day + + ;

break ; /* exit loop*/ }

printf ( “ Enter temperature for day %d : “, day ) ; scanf ( “ %f “, %temper [ day ] ) ;

}

(8)

Initializing Arrays

• Suppose we want to compile our program with

specific values already fixed in the array.

• This is analogous to initializing a simple variable

i.e. int marks = 45

# define LIM 5

int table [ LIM ] = { 50, 25, 10, 5,1 } ;

void main (void) {

int count , a[5] = { 10, 20, 30, 40, 50 } ; for (count=0; count < 5; count++)

{

printf("Value of array [%d] is = %d \n", a[count] ); }

getch( ); }

Output

(9)

Array Size and Initialization

• There is a change in the array definition in the previous two programs.

int table [ 5 ] = { 50, 25, 10, 5,1 } ;

static int table [ ] = { 50, 25, 10, 5,1 } ;

• If no number is supplied for the size of the array, the compiler will very kindly count the number of items in the initialization list and fix that as the array size.

• If the number is larger than the number of items, the extra spaces in the array will be filled in with zeros. If the number is too small, the compiler will complain.

Array Contents and Initialization

• If we execute an array declaration like this, what will be the output?

void main() {

int array[10];

printf(“Array element 3 has the value %d”,array[3]); }

• Garbage value will be printed i.e. whatever value is sitting in that particular part of memory before the function was called and the array declared.

(10)

Preprocessor Directives

• Normal program statements are instructions to the

microprocessor ; Preprocessor directives are

instructions to the compiler

• Rather than being translated into machine language,

they are operated on directly by the compiler before

the compilation process even begins; hence the

name preprocessor.

• Preprocessor directives always start with a number

sign (

#

)

• The directives can be placed anywhere in a

program, but are often used at the beginning of a

file, before main ( ), or before the beginning of

particular functions.

More than One Dimension

• It is also possible to have two or more dimensions of an array. • This permits them to emulate or model multi-dimensional

objects such as graph paper or computer screen itself. • C stores two-dimensional arrays in row-major order.

• The elements of row 0 come first, followed by the elements of row 1, and so forth. An array with r rows would have the following appearance:

one

(11)

This program records, not one list of data as our previous programs have, but 2 lists side-by-side. It stores the travel expenses for a no. of secret agents who are known only by their code numbers.

# define ROWS 10 # define COLS 2

void main (void) {

float number, expenses ; float agents [ROWS] [COLS] ; int index = 0, outdex ;

printf ( “Enter 3-digit Agent number , \n “ ) ; printf ( “Travel expenses i.e. ( 007 1500.50 ) \n “ ) ; printf ( “Enter 0 0 to quit \n “ ) ;

# define directive

Identifier– ROW

Text – 10

ROW and COLS will be replaced by 10 & 2 resp.

do */ get list of agents and expenses*/ {

printf ( “ Agent’s number and expenses: “ ) ; scanf ( “ %f %f “, &number, &expenses ) ; agents [ index ] [ 0 ] = number ;

agents [ index ] [ 1 ] = expenses ; }

while ( agent [ index ++ ] [ 0 ] ! = 0 ) ;

for ( outdex = 0 ; outdex < index - 1; outdex + + ) { */ print list */

printf ( “ Agent %03.0f “, agent [ outdex ] [ 0 ] ) ; printf ( “ Spent %7.2f. \n “, agent [ outdex ] [ 1] ) ; }

(12)

Output:

Enter 3-digit Agent number:

Travel expenses i.e. ( 007 1500.50 ): Enter 0 0 to quit:

Agent’s number and expenses : 101 2331.50 Agent’s number and expenses : 007 8640 Agent’s number and expenses : 901 123.25 Agent’s number and expenses : 904 500.6 Agent’s number and expenses : 0 0 Agent 101 spent 2331.50

Agent 7 spent 8640 Agent 901 spent 123.25 Agent 904 spent 500.60

• There are 2 parts to the program

– A do-while loopthat gets the data from the user and stores it in the 2-dimensional array table[ ][ ].

• Instead of getting only one piece of data each time through the loop, we get two; placing them in the variables agents[index][0] and agents[index][1]with the scanf()statement.

scanf ( “ %f %f “, & agents[index][0], & agents[index][1] ) ;

– A for loopthat prints out the contents of the array.

• Entire array is of type float, but decimal places are not printed in agent numbers. Reason for float data type is we want to use dollars and cents for expenses.

(13)

9 8 7 6 5 4

500.60 904

3

123.25 901

2

8640.00 007

1

2331.50 101

0

Column 1 Column 0

row

agents [2] [0]

agents [4] [1]

agents [index] [0]

this is the row this is the column

Initializing 2-Dimensional Arrays

• The value used to initialize an array are separated by commas and surrounded by braces.

void main (void) {

int table [5] [2] = { {1,2}, {3,4}, {5,6}, {7,8}, {9,0} } ; int x, y ;

printf (“Initializing a 2-Dimensional Array “) ; for ( x = 0 ; x < 5 ; x ++ )

{ for ( y = 0 ; y < 2 ; y ++ )

printf ( “ %d \t “, table[ x ] [ y ] ) ; }

(14)

Output:

1 2 3 4 5 6 7 8 9 0

You can also write the array like this:

int table [ 5 ] [ 2 ] = { { 1 , 2 } , { 3 , 4 } , { 5 , 6 } , { 7 , 8 } , { 9 , 0 } } ;

Columns 0 9 4 8 7 3 6 5 2 4 3 1 2 1 0 1 0 row

Initializing 3-Dimensional Arrays

int table [ 3 ] [ 2 ] [ 4 ] = { { { 1, 2, 3, 4 } ,

{ 5, 6, 7, 8 } , } , { { 7, 9, 3, 2 } ,

{ 4, 6, 8, 3 } , } , { { 7, 2, 6, 3 } ,

{ 0, 1, 9, 4 } , } , };

• This is an array of arrays. The outer array has three elements, each of which is a 2-dimensional array of two elements, each of which is a one-dimensional array of four numbers.

• table [2] [1] [0] = = 0 is true or not?

– First subscript is [2], as it’s the third group of 3 2D arrays. – Second subscript is [1], its in the second of 2 1D array. – Third subscript is [0], it’s the first element in the 1D array.

So its true.

(15)

Arrays as Arguments

# define MAXSIZE 20

int max ( int [ ] , int ) ; void main (void)

{

int list [ MAXSIZE ] , num, size = 0 ; do

{

printf ( “ Type number: “ ) ; scanf ( “ %d “, &list [ size ] ) ; }

while ( list [ size ++ ] ! = 0 ) ; size--;

num = max ( list, size-1 );

printf ( “ Largest number is %d “, num ) ; getch ( ) ;

}

Arrays as Arguments

int max ( int list [ ] , int size )

{

int dex, max ; max = list [ 0 ] ; for (dex = 1 ; dex < size ; dex + + )

if ( max < list [ dex ] ) max = list [ dex ] ; rerurn ( max ) ;

}

Output

(16)

Arrays as Arguments

• In the above program there is a new element here in this statement:

num = max ( list, size-1 ) ;

• This is call to the function max ( ), which returns the largest number. There are two arguments to the function: the first is the array list, the second is the variable size.

• Lets imagine an integer variable num with a value 25, initialize like this: int num = 25 ;

• Here 4 things to know about the variable:

Name of the variable: num Value of the variable: 25 Name of the address: &num Address of the variable: 1234 (suppose) • Now lets see what a similar representation looks like for an

array.

An array is referred to by its address, which is represented by the name of the array, used without subscripts.”

• Value of the ( First ) element of the Array: 11 • Address of the Array: 1500 • Name of element in Array: list [ 0 ] • Name of the address of the Array: list • Name of the address of elements in the Array: &list [ 0 ]

Why is not the address of the array called something like &list?

• consistent with the way the address of variables are named, but it would leave the word “list”, which is not used to name anything else about the variable

• list refers to an address if list is an array, but would refer to a value if list were a simple variable

• Since list [ 0 ] is the first element of the array, it will have the same address as the array itself. And since & is the address operator, &list [ 0 ] gives the address of the first element of the array. In other words:

(17)

• To summarize, to tell the compiler the address of array, we use the name of the array, with no brackets following it.

• Thus call to the function max() passes the address of array, represented by the word list, to the function.

• When a simple variable name is passed to the function , it takes the value corresponding to this variable name and installs it as a new variable in a new memory location created by the function for that purpose.

• Since arrays can be very large, it is better to have only one copy of array, no matter how many functions wanted to access it. • So instead of passing the values in the array, only address of

array is passed.

• The function then uses the address to access the original array. • So passing an array name to function does not create a new

References

Related documents

Pointers and Arrays With a regular array declaration you get a pointer for free The name of the array acts as a pointer to the first element of the array int list10.. Recall that

The main optimization of antichain-based algorithms [1] for checking language inclusion of automata over finite alphabets is that product states that are subsets of already

In this study, it is aimed to develop the Science Education Peer Comparison Scale (SEPCS) in order to measure the comparison of Science Education students'

(XXXXX = Progressive serial number corresponding to lot entry in production diary which contains all information required

Sau khi khai báo xong đèn báo lỗi sẽ sáng, bật công tắc nguồn của ngăn chỉnh lưu về trạng thái ON, đèn báo lỗi tắt, thông báo lỗi trên màn hình sẽ được

• Under ECLGS 2.0(Extension), the amount of GECL funding to eligible borrowers either in the form of additional working capital term loan facility and / or non-Fund based facility or

 A particular value in an array is referenced using the array A particular value in an array is referenced using the array name followed by the index in brackets.. name followed

Similarly, nearly 78% of the respondents in (Vicknasingam et al., 2010) study reported that they were unable to quit from ketum use. Previous studies on ketum use in humans