Sei sulla pagina 1di 67

CS1010E Lecture 5

Arrays
Semester 1 2015 / 2016

Lecture Outline
Motivation
What is an Array
1D array and 2D arrays:
Declaration and access
Initialization
Problem solving with arrays

Motivation

Motivation
I have a set of daily temperature readings
collected over 3 days and I want to write a
program to find the median temperature
(assuming all the readings are unique)
How to represent these set of temperature
readings in my program?

Motivation
Write a program using 3 floating point variables
#include <stdio.h>
int main(void) {
double r1, r2, r3;

scanf("%lf",&r1);
scanf("%lf",&r2);
scanf("%lf",&r3);
return 0;

Motivation
But how to find the median after I have
captured the readings?

Motivation
But how to find the median after I have
captured the readings?
int main(void) {
double r1, r2, r3;
scanf("%lf",&r1);
scanf("%lf",&r2);
scanf("%lf",&r3);

if ((r2 <= r1 && r1


printf("median =
if ((r1 <= r2 && r2
printf("median =
if ((r2 <= r3 && r3
printf("median =

<= r3) || (r3 <= r1 && r1 <= r2))


%f",r1);
<= r3) || (r3 <= r2 && r2 <= r1))
%f",r2);
<= r1) || (r1 <= r3 && r3 <= r2))
%f",r3);

return 0;
}

Motivation
What if I have the readings for a week?
What if I have the readings for a month?
What if I have the readings for a year?
My program is not scalable!

Motivation
Need a way to represent the multiple
temperature readings as a collection in my
program and be able to manipulate the
collection efficiently
This is where arrays come in !

What is an Array?

10

What is an Array?
An array is a fixed-sized sequential collection of
data of the same type.
E.g array of integers, array of floating points etc.

All arrays consist of contiguous memory


locations and the data are stored consecutively
Allows for fast access

11

What is an Array?
First element
(at lowest memory address)

100

Last element
(at highest memory address)

231

500

Conceptual drawing of an integer array of size 5

12

1D Array declaration and access

13

Declaring 1D Array
Declaration format
Type arrayName[arraySize];
Type int, double
arrayName variable name of 1D array
arraySize An expression that evaluates to an
integer indicating the size of the array
14

Declaring 1D Array
Fixed-sized Array
arraySize is a constant expression, and is known
during compile time

Example
#define M 10;
int main(void) {
double array1[7];
double array2[M];

15

Accessing 1D Array Elements


Two ways to access elements in a 1D array
Subscript based indexing
Pointer based indexing

Will discuss after


introducing pointers in
a later lecture

16

Subscript based indexing of 1D Array


Subscript based indexing
arrayName[elementIndex]

elementIndex Any integer expression


arrayName[0] accesses 1st element in the array
(also known as 0-based indexing)
arrayName[arraySize-1] accesses last element in
the array
A subscripted array variable is an expression (like
any other variable)
17

Subscript based indexing of 1D Array


tempReading

32.0

25.8

27.3

28.1

25.0

33.3

30.9

int curIndex = 3;
double t = 10.0;
printf("%f\n",tempReading[0]);
printf("%f\n",tempReading[1]);
printf("%f\n",tempReading[6]);
printf("%f\n",tempReading[curIndex+2]);
t = t + tempReading[curIndex+2]; /* t==43.3 */

Used in an expression
like any other variable
18

Subscript based indexing of 1D Array


tempReading

32.0

25.8

27.3

28.1

25.0

33.3

30.9

43.3

int curIndex = 3;
double t = 10.0;
tempReading[curIndex+2] = t + tempReading[curIndex+2];
Assign the value of tempReading[curIndex+2] just like any other variable

19

1D Array Initialization

20

Initializing 1D Array
In most cases, an array is created with unknown
values in it
Usually we want the array to be filled with some
valid starting value(s)
Initialization is the process of specifying the
starting values in an array

21

Initializing 1D Array
Using initialization lists
Can only be used during declaration of the array

double tempReading[7] = {32.0,25.8,27.3,28.1,25.0,33.3,30.9};

Initialization list

tempReading

32.0

25.8

27.3

28.1

25.0

33.3

30.9

22

Initializing 1D Array
Cannot perform declaration style initialization
after the declaration of an array
double tempReading[7];
tempReading = {32.0, 25.8, 27.3, 28.1, 25.0, 33.3, 30.9};

Gives a compilation error

23

Initializing 1D Array
Initialization list may be shorter than the size of
the array (rest of entries initialized to 0)
double tempReading[7] = {32.0, 25.8};

tempReading

32.0

25.8

0.0

0.0

0.0

0.0

0.0

The rest of the entries are initialized to 0

To zero the entire array


double tempReading[7] = {0.0};
24

Solving problems using 1D Array

25

Going through entire 1D Array


Depending on the problem
Go through array from left to right
Go through array from right to left
Or some other variation

26

Going through entire 1D Array


Left to Right

27

Going through entire 1D Array


Left to Right

Use a for loop !


28

Going through entire 1D Array


Left to Right

29

Going through entire 1D Array


Left to Right
#include <stdio.h>
#define SIZE 11
int main(void) {
int i, sq[SIZE];
for (i = 0; i < SIZE; i++)
sq[i] = i*i;

Home Work:
Try and fill it from
right to left !

for (i = 1; i < SIZE; i++)


printf("%d ", sq[i]);
printf("\n");
return 0;

30

Example: reading and printing array

31

Example: reading and printing array


Using initial count
#include <stdio.h>
#define SIZE 100
int main(void) {
double tempReading[SIZE] = {0.0};
int numReadings, i;
double reading;
scanf("%d",&numReadings);
for (i = 0; i < numReadings; i++) {
scanf("%lf",&reading);
tempReading[i] = reading;
}
return 0;

}
32

Example: reading and printing array


Using initial count
#include <stdio.h>
#define SIZE 100
int main(void) {
double tempReading[SIZE] = {0.0};
int numReadings, i;
scanf("%d",&numReadings);
for (i = 0; i < numReadings; i++) {
scanf("%lf",&tempReading[i]);
}

Alternative

return 0;
}

33

Example: reading and printing array


Using initial count
#include <stdio.h>
#define SIZE 100
int main(void) {
double tempReading[SIZE] = {0.0};
int numReadings, i;
scanf("%d",&numReadings);
for (i = 0; i < numReadings; i++) {
scanf("%lf",&tempReading[i]);
}
for (i = 0; i < numReadings; i++)
printf("%f ",tempReading[i]);

return 0;
}

34

Example: Median Temperature


How to do this using an array of temperature
readings?

35

Example: Median Temperature


Assuming number of readings is odd
#include <stdio.h>
#define SIZE 100
int main(void) {
double tempReading[SIZE] = {0.0};
int numReadings, i, j, medianPos, numBiggerEq;

scanf("%d",&numReadings);
for (i = 0; i < numReadings; i++) {
scanf("%lf",&tempReading[i]);
}
medianPos = (numReadings+1)/2;
i = -1;
do {
numBiggerEq = 0;
i = i + 1;
for (j = 0; j < numReadings; j++)
if (tempReading[i] >= tempReading[j])
numBiggerEq += 1;
} while (numBiggerEq != medianPos)
printf("median = %f \n",tempReading[i]);
return 0;
}

36

Example: Median Temperature


If we can sort the temperature readings in our
array then it is even easier to find the median !
Well deal with sorting in a later lecture
What if number of readings is even? (try to
solve this yourself)

37

2D Array
declaration and access

38

2D Array
2D arrays are useful when representing a
table/matrix of data
Each element is stored in a particular cell
referenced by row followed by column
(row,col)
0

Columns
1

Rows 1

4 is at cell (1,2)

A 3-by-3 (#row-by-#column) 2D array of integers

39

Declaring 2D array
Declaration
Type arrayName[rowSize][colSize];

Type int, double


arrayName variable name of the 2D array
rowSize number of rows of the 2D array
colSize number of columns of the 2D array

*2D arrays are assumed to be in row-major form


(that is row followed by column)

40

Declaring 2D Array
E.g
Can store a total of 4*3 = 12 integers

int t[4][3];

Declares a 4-by-3 array of integers

41

Accessing 2D Array Elements


Similar to 1D arrays, two ways to access elements
in a 2D array are
Subscript based indexing
Pointer based indexing

Will discuss after


introducing pointers in
a much later lecture

42

Accessing 2D Array Elements


Subscript Based
Each element in a 2D array is referenced as follows
arrayName[rowIndex][colIndex]
rowIndex, colIndex
any expression that evaluates to an integer value
0 <= rowIndex < rowSize
0 <= colIndex < colSize
43

Accessing 2D Array Elements Subscript Based


arrayName[0][0] accesses element at top left
corner of the 2D array (usually referred to as 1st
element)
arrayName[rowSize-1][colSize-1] accesses
element at bottom right corner of the 2D array
(usually referred to as last element)
t

For the example to the right


Value at entry t[1][2] is 5
Value at entry t[2][1] is 6
44

2D arrays are 1D arrays in C !


2D arrays are actually 1D arrays in C in terms
of how they are stored in memory
It is one continuous linear block of memory

Example a 2-by-3 array will look as follows


1st row

2-by-3 array

2nd row

Linearly stored in memory

45

2D Array
Initialization

46

2D Array Initialization
Initialization using initialization list
Can only be done during declaration

int t[4][3] = {{2,3,-1},


{0,-3,5},
{2,6,3},
{-2,10,4}};

Initializer/Initializer sequence

47

2D Array Initialization
If the initializer sequence is shorter than the
array, the rest is initialized to zero
To zero the entire array
int t[4][3] = {{0}};

48

Solving problems using 2D Array

49

Going through entire 2D Array


Depending on the problem
Go through 2D array from left to right, top to
bottom

Go through array from right to left, bottom to top

Or some other variation


50

Going through entire 2D Array


Left to Right, Top to Bottom

Use 2 for loop !

51

Going through entire 2D Array


Left to Right, Top to Bottom
Example Compute 10-by-10 multiplication
table

52

Going through entire 2D Array


Left to Right, Top to Bottom
Example Compute 10-by-10 multiplication
#include <stdio.h>
table
#define N 11
#define M 11
int main(void) {
int row, col, mulTable[N][M];
for (row = 0; row < N; row++)
for (col = 0; col < M; col++) {
mulTable[row][col] = row*col;
}
for (row = 1; row < N; row++) {
for (col = 1; col < M; col++) {
printf("%4d", mulTable[row][col]);
}
printf("\n");
}
return 0;
53

Home Work:
Try and fill it from
right to left,
bottom to top !
}

Example: 2D Cumulative Sum

54

Example: 2D Cumulative Sum

Original array

Cumulative sum array

55

Example: 2D Cumulative Sum

Original array

Cumulative sum array

56

Example: 2D Cumulative Sum

Original array

Cumulative sum array

57

Example: 2D Cumulative Sum

Original array

Cumulative sum array

58

Example: 2D Cumulative Sum

Original array

Cumulative sum array

59

Example: 2D Cumulative Sum

Original array

Cumulative sum array

60

Example: 2D Cumulative Sum

Original array

Cumulative sum array

61

Example: 2D Cumulative Sum

Original array

Cumulative sum array

62

Example: 2D Cumulative Sum

63

Example: 2D Cumulative Sum


#include <stdio.h>
#define SIZE 100
int main(void) {
int nRows, nCols, i, j, m, n;
int t[SIZE][SIZE]={{0}};
int s[SIZE][SIZE]={{0}};
scanf("%d%d", &nRows, &nCols);
for (i = 0; i < nRows; i++)
for (j = 0; j < nCols; j++)
scanf("%d", &(t[i][j]));
for (i = 0; i < nRows; i++)
for (j = 0; j < nCols; j++)
for (m = 0; m <= i; m++)
for (n = 0; n <= j; n++)
s[i][j] += t[m][n];
for (i = 0; i < nRows; i++) {
for (j = 0; j < nCols; j++)
printf("%4d", s[i][j]);
printf("\n");
}
return 0;
}

64

Pitfalls in accessing array elements

65

Pitfalls in [] usage
Differentiate the use of [] in
Declarations
Statements

allocate memory for arrays


indexing/subscripting

66

Lecture Summary
1D arrays
Declaration/initialization with pre-determined size
Subscripting to assess individual elements
Loops to access array elements

2D arrays are simply extensions of 1D arrays

67

Potrebbero piacerti anche