You are on page 1of 30

CSCE150A

Computer Science & Engineering 150A


Introduction

Declaring,
Problem Solving Using Computers
Referencing

Initialization Lecture 06 - Arrays


Function Args

Constants

Returning
Arrays Stephen Scott
Searching & Adapted from Christopher M. Bourke
Sorting

Multi-
dimensional
Arrays

Common
Errors
Fall 2009
Exercises
1 / 30
Chapter 8

CSCE150A

Introduction 8.1 Declaring and Referencing Arrays


Declaring,
Referencing
8.2 Array Subscripts
Initialization 8.3 Using For Loops for Sequential Access
Function Args
8.4 Using Array Elements as Function Arguments
Constants

Returning
8.5 Array Arguments
Arrays
8.6 Searching and Sorting an Array
Searching &
Sorting 8.7 Multidimensional Arrays
Multi-
dimensional 8.9 Common Programming Errors
Arrays

Common
Errors

Exercises
2 / 30
Introduction

CSCE150A

Introduction

Declaring,
Referencing
Simple data types use a single memory cell to store a variable
Initialization Collections of data should be logically grouped
Function Args
Example: 75 students in the class; should we declare 75 separate
Constants
variables to hold grades?
Returning
Arrays Grouping related data items together into a single composite data
Searching &
Sorting
structure is done using an array
Multi-
dimensional
Arrays

Common
Errors

Exercises
3 / 30
Declaring Arrays I

CSCE150A

Introduction

Declaring,
Referencing

Initialization An array is a collection of two or more adjacent memory cells, called


Function Args array elements
Constants
All elements in an array are associated with a single variable name
Returning
Arrays Each element is individually accessed using indices
Searching &
Sorting

Multi-
dimensional
Arrays

Common
Errors

Exercises
4 / 30
Declaring Arrays II

CSCE150A

To set up an array in memory, we declare both the name of the array


Introduction and the number of cells associated with it:
Declaring,
Referencing
double my_first_array[8];
int students[10];
Initialization

Function Args
The first one instructs C to associate 8 memory cells of type double
Constants
with the name my_first_array
Returning
The second one instructs C to associate 10 memory cells of type int
Arrays with the name students
Searching &
Sorting In all cases, the memory cells will be adjacent to each other in
Multi- memory
dimensional
Arrays

Common
Errors

Exercises
5 / 30
Referencing Array Elements I

CSCE150A

Introduction

Declaring,
Referencing To process the data stored in an array, each individual element is
Initialization associated to a reference value
Function Args
By specifying the array name and identifying the element desired, we
Constants
can access a particular value
Returning
Arrays
The subscripted variable x[0] (read as x sub zero) references the
Searching &
Sorting first element
Multi-
dimensional
Arrays

Common
Errors

Exercises
6 / 30
Referencing Array Elements II

CSCE150A

Other elements can be accessed similarly: x[1], x[2], ...


Introduction
myArray[0] = 8;
Declaring,
Referencing printf("value of second element=%d",myArray[1]);
Initialization scanf("input a number: %d",&anotherArray[9]);
Function Args
For an array of size n, we index 0, 1, . . . , n − 1
Constants
Think of index as an offset from base address
Returning
Arrays
An array size must be an integer (no such thing as half an element)
Searching &
Sorting Similarly, each index is also an integer
Multi-
dimensional
Arrays

Common
Errors

Exercises
7 / 30
Referencing Array Elements I
Pitfall

CSCE150A

Take care that you do not reference an index outside the array:
Introduction

Declaring,
1 double grades [75];
Referencing 2 ...
Initialization 3 printf ( " 75 th grade is % f \ n " , grades [74]);
Function Args
4 printf ( " 76 th grade is % f \ n " , grades [75]); ← Illegal
5 printf ( " -1 th grade is % f \ n " , grades [ -1]); ← Illegal
Constants
6
Returning
Arrays 7 int i ;
Searching &
8 for ( i =0; i <76; i ++)
Sorting 9 printf ( " %d - th grade is % f \ n " , ( i +1) , grades [ i ]);
Multi- 10 ↑ Illegal on last iteration
dimensional
Arrays

Common
Errors

Exercises
8 / 30
Array Initialization

CSCE150A

Introduction
You can declare multiple arrays along with regular variables:
Declaring, double cactus[5], needle, pins[7];
Referencing

Initialization
We can initialize a simple variable when we declare it:
Function Args
int sum = 0;
Constants Same with arrays:
Returning
Arrays 1 int array [ SIZE ];
Searching & 2 for ( i =0; i < SIZE ; i ++)
Sorting

Multi-
3 array [ i ] = 0;
dimensional
Arrays

Common
Errors

Exercises
9 / 30
Array Declaration & Initialization

CSCE150A

Introduction

Declaring,
We can declare and initialize an array
Referencing
If we initialize when we declare, we can omit the size
Initialization

Function Args
1 int p r i m e N u m b e r s L e s s T h a n H u n d r e d [] = {
Constants

Returning
2 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 ,
Arrays 3 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 ,
Searching &
Sorting
4 89 , 97 };
Multi-
dimensional
Arrays

Common
Errors

Exercises
10 / 30
Using for Loops for Sequential Access

CSCE150A

Elements of an array are processed in sequence, starting with element


Introduction zero.
Declaring,
Referencing
This processing can be done easily using an indexed for loop: a
Initialization counting loop whose loop control variable runs from zero to one less
Function Args than the array size.
Constants Using the loop counter as an array index (subscript) gives access to
Returning
Arrays
each array element in turn.
Searching &
Sorting 1 for ( i =0; i < SIZE ; i ++) {
Multi-
dimensional
2 printf ( " % d " , array [ i ]);
Arrays
3 }
Common
Errors

Exercises
11 / 30
Using Array Elements as Function Arguments

CSCE150A

Introduction

Declaring,
Referencing
You can use scanf with array elements just like with regular variables
Initialization 1 int x [10];
Function Args 2 int i = 0;
Constants
3 scanf ( " % d " , & x [ i ]);
Returning
Arrays 4 printf ( " Hey , I read % d \ n " , x [ i ]);
Searching &
Sorting

Multi-
dimensional
Arrays

Common
Errors

Exercises
12 / 30
Arrays as Arguments

CSCE150A

You can also use entire arrays as function arguments


Introduction

Declaring,
Passing arrays as arguments to a function means:
Referencing The function can access any value in the array
Initialization The function can change any value in the array
Function Args
Syntax: specify an array as a parameter by using the square brackets:
Constants
int sum(int array[], int size);
Returning
Arrays
Note: what is actually being passed is a pointer to the first element
Searching &
Sorting of the array!
Multi- We could equivalently define:
dimensional
Arrays int sum(int *array, int size);
Common
Errors

Exercises
13 / 30
Full Example

CSCE150A

1 # include < stdio .h >


2
Introduction 3 int sum ( int array [] , int size );
4
Declaring, 5 int main ( void )
Referencing 6 {
7 int foo [] = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10} , i ;
Initialization 8 printf ( " sum of all array elements is % d \ n " , sum ( foo , 10));
9 return 0;
Function Args 10 }
11
Constants 12 int sum ( int a [] , int size )
13 {
Returning
14 int i , summation = 0;
Arrays
15 for ( i =0; i < size ; i ++)
Searching & 16 {
Sorting 17 summation += a [ i ];
18 }
Multi- 19 return summation ;
dimensional 20 }
Arrays

Common
Errors

Exercises
14 / 30
Formal Array Parameter

CSCE150A

Introduction It was necessary to pass an additional variable size to sum


Declaring,
Referencing
An array does not have an explicit size associated with it
Initialization C does not allocate space in memory for arrays; the operating system
Function Args does this at runtime
Constants
As programmers, we are responsible for:
Returning
Arrays Memory management
Searching & For keeping track of the size of an array
Sorting For ensuring that we do not access memory outside the array
Multi-
dimensional If a function accesses an array, it needs to be told how big it is
Arrays

Common
Errors

Exercises
15 / 30
Arrays as Input Arguments

CSCE150A

Since arrays are passed by reference (like scanf), functions can


Introduction
modify their values
Declaring,
Referencing Sometimes, we would like to pass arrays as arguments, but do not
Initialization
want to change their values.
Function Args
We can do this by using the const quantifier in the function
Constants

Returning
declaration: int sum(const int foo[], int size) ...
Arrays
Specifies to the compiler that the array is to be used only as an input
Searching &
Sorting The function does not intend to modify the array
Multi-
dimensional The compiler enforces this: any attempt to change an array element
Arrays
in the function as an error
Common
Errors

Exercises
16 / 30
Returning an Array Result

CSCE150A

C only allows us to return a single item


Introduction

Declaring, It is not possible to return an array (a collection of items)


Referencing
We can, however, return a pointer to an array
Initialization

Function Args We cannot return a pointer to a local array (dangerous; undefined


Constants behavior)
Returning
Arrays
Requires knowledge of dynamic memory and malloc
Searching & More later this semester; for now: simply declare an array large
Sorting
enough for your purposes
Multi-
dimensional Might need two controlling variables: one for max array size and one
Arrays for number of cells used
Common
Errors

Exercises
17 / 30
Searching and Sorting an Array

CSCE150A

Introduction

Declaring,
Referencing

Initialization
Two common problems with array processing:
Function Args
1 Searching - Finding the index of a particular element in an array
Constants

Returning
2 Sorting - rearranging array elements in a particular order
Arrays

Searching &
Sorting

Multi-
dimensional
Arrays

Common
Errors

Exercises
18 / 30
Searching an Array

CSCE150A

1 Assume the target has not been found


Introduction 2 Start with the initial array element, a[0]
Declaring, 3 while the target is not found and there are more array elements
Referencing do
Initialization 4 if the current element matches array then
Function Args 5 set flag true and store the array index
Constants 6 end
Returning 7 advance to next array element
Arrays
8 end
Searching &
Sorting 9 if flag is set to true then
Multi- 10 return the array index
dimensional
Arrays 11 end
Common 12 return -1 to indicate not found
Errors

Exercises
Algorithm 1: Searching Algorithm
19 / 30
Searching an Array
C code

CSCE150A 1 int search ( int array [] , int size , int target )


2 {
3 int found = 0 , index = -1;
Introduction 4 while ( ! found && ( i < size ) )
Declaring,
5 {
Referencing 6 if ( array [ i ] == target ) {
Initialization 7 found = 1;
Function Args 8 index = i ;
Constants
9 }
10 else {
Returning
Arrays 11 i ++;
Searching &
12 }
Sorting 13 }
Multi- 14 if ( found )
dimensional 15 return index ;
Arrays
16 else
Common
Errors 17 return -1;
Exercises
18 }
20 / 30
Sorting an Array - Selection

CSCE150A

Introduction

Declaring,
Referencing 1 foreach index value i = 0, . . . , n − 2 do
Initialization 2 Find the index of the smallest element in the
Function Args subarray a[i, . . . , n − 1]
Constants 3 Swap the smallest element with the element
Returning
stored at index i
Arrays 4 end
Searching &
Sorting Algorithm 2: Selection Sort Algorithm
Multi-
dimensional
Arrays

Common
Errors

Exercises
21 / 30
Sorting an Array - Selection

CSCE150A 1 void selectionSort ( int *a , int size )


2 {
3 int i , j , minimum_index , temp ;
Introduction 4 for ( i =0; i < size -2; i ++)
Declaring,
5 {
Referencing 6 minimum_index = i ;
Initialization 7 for ( j = i +1; j < size ; j ++)
Function Args 8 {
Constants
9 if ( a [ minimum_index ] > a [ j ])
10 {
Returning
Arrays 11 index_of_min = j ;
Searching &
12 }
Sorting 13 }
Multi- 14 temp = a [ i ];
dimensional 15 a [ i ]] = a [ minimum_index ];
Arrays
16 a [ minimum_index ] = temp ;
Common
Errors 17 }
Exercises
18 }
22 / 30
Sorting an Array - Bubble Sort

CSCE150A

Introduction

Declaring, 1 while i ≤ n − 1 do
Referencing
2 while j ≤ n − 1 do
Initialization
3 if a[j] > a[j + 1] then
Function Args 4 Swap a[j] and a[j + 1]
Constants 5 end
Returning
Arrays
6 end
Searching & 7 end
Sorting

Multi-
Algorithm 3: Bubble Sort Algorithm
dimensional
Arrays

Common
Errors

Exercises
23 / 30
Sorting an Array - Bubble Sort
C code

CSCE150A 1 void bubbleSort ( int *a , int size )


2 {
3 int i , j , temp ;
Introduction 4 for ( i =0; i < size -1; i ++)
Declaring, 5 {
Referencing
6 for ( j =0; j < size -1; j ++)
Initialization
7 {
Function Args
8 if ( a [ j ] > a [ j +1])
Constants
9 {
Returning
Arrays
10 temp = a [ j ];
Searching &
11 a [ j ] = a [ j +1];
Sorting 12 a [ j +1] = temp ;
Multi- 13 }
dimensional
Arrays 14 }
Common 15 }
Errors 16 }
Exercises
24 / 30
Multidimensional Arrays I

CSCE150A

Introduction

Declaring, A multidimensional array is an array with two or more dimensions


Referencing

Initialization
Two-dimensional arrays represent tables of data, matrices, and other
Function Args
two-dimensional objects
Constants Declare multidimensional arrays similar to regular arrays:
Returning
Arrays
int myArray[10][20];
Searching & This declares a 10 × 20 sized array
Sorting

Multi-
Interpretation: 10 rows, 20 columns
dimensional
Arrays

Common
Errors

Exercises
25 / 30
Multidimensional Arrays II

CSCE150A

Each row/column is still indexed 0, . . . , n − 1 and 0, . . . , m − 1


Introduction

Declaring,
Last row, last column: myArray[9][19] = 29;
Referencing
When iterating over a multidimensional array, use nested for loops
Initialization

Function Args

Constants
1 int a [10][10];
Returning
2 for ( i =0; i <10; i ++)
Arrays 3 for ( j =0; j <10; j ++)
Searching &
Sorting
4 a [ i ][ j ] = 1 + i + j ;
Multi-
dimensional
Arrays

Common
Errors

Exercises
26 / 30
Initialization of Multidimensional Arrays

CSCE150A

Introduction

Declaring, You can initialize multidimensional arrays when declaring


Referencing

Initialization 1 char tictactoe [][3] = { { ’ ’ , ’ ’ , ’ ’} ,


Function Args 2 { ’ ’ , ’ ’ , ’ ’} ,
Constants 3 { ’ ’ , ’ ’ , ’ ’} };
Returning
Arrays

Searching &
Sorting
This would initialize a 3 × 3 the array with all blank spaces.
Multi-
dimensional
Arrays

Common
Errors

Exercises
27 / 30
Initialization of Multidimensional Arrays

CSCE150A

Introduction

Declaring,
Referencing When declaring and initializing, you must still provide all dimensions
Initialization except the outer-most
Function Args
The compiler is able to deduce the outer-most dimension at compile
Constants

Returning
time
Arrays
Not sophisticated enough to deduce the rest
Searching &
Sorting

Multi-
dimensional
Arrays

Common
Errors

Exercises
28 / 30
Common Programming Errors

CSCE150A

Introduction

Declaring,
Referencing

Initialization
Most common error: out-of-range access error
Function Args
Segmentation fault, Bus error
Constants
Error may not be caught in some situations: unexpected results
Returning Use correct syntax when passing arrays as parameters
Arrays

Searching &
Sorting

Multi-
dimensional
Arrays

Common
Errors

Exercises
29 / 30
Exercises

CSCE150A

Introduction Write the following functions and write a main driver program to test
Declaring, them.
Referencing

Initialization
void printArray(int *array, int size) – prints the elements
Function Args
of an integer array
Constants

Returning
void printMatrix(int **array, int rows, int columns) –
Arrays prints the elements of an integer array
Searching &
Sorting double average(int *array, int size) – computes the
Multi- average of all elements in the array
dimensional
Arrays

Common
Errors

Exercises
30 / 30

You might also like