WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays Prof. - - PowerPoint PPT Presentation

with c
SMART_READER_LITE
LIVE PREVIEW

WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays Prof. - - PowerPoint PPT Presentation

CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays Prof. Amr Goneid, AUC 1 Arrays Prof. Amr Goneid, AUC 2 1-D Arrays Data Structures The Array Data Type How to Declare an Array


slide-1
SLIDE 1
  • Prof. Amr Goneid, AUC

1

CSCE 110 PROGRAMMING FUNDAMENTALS

WITH C++

  • Prof. Amr Goneid

AUC Part 7. 1-D & 2-D Arrays

slide-2
SLIDE 2
  • Prof. Amr Goneid, AUC

2

Arrays

slide-3
SLIDE 3
  • Prof. Amr Goneid, AUC

3

1-D Arrays

 Data Structures  The Array Data Type  How to Declare an Array  Operations on Arrays  Passing to and from Functions  Examples  Example Functions

slide-4
SLIDE 4
  • Prof. Amr Goneid, AUC

4

  • 1. Data Structures

Data Set Linear Tree Graph

slide-5
SLIDE 5
  • Prof. Amr Goneid, AUC

5

Data Structures

 Sets: No structure, just membership.  Linear: Sequential, one-to-one.

e.g Arrays, Strings and Streams

 Tree: Non-Linear, one-to-many.  Graph: Non-Linear, many-to-many.

Arrays, Structures and Classes are used to model different data structures.

slide-6
SLIDE 6
  • Prof. Amr Goneid, AUC

6

  • 2. The Array Data Type

 Array elements have a common name

 The array as a whole is referenced through the

common name  Array elements are of the same type — the

base type

 Individual elements of the array are

referenced by sub_scripting the group name by an index

slide-7
SLIDE 7
  • Prof. Amr Goneid, AUC

7

1-D Arrays

slide-8
SLIDE 8
  • Prof. Amr Goneid, AUC

8

1-D Arrays

 Linear Data Structure (One-To-One)  Fixed Size n (Static)  All elements are of the same type  An element is accessed by an ordinal index

with values between a lower bound (0) and an upper bound (n-1)

n -1 index

slide-9
SLIDE 9
  • Prof. Amr Goneid, AUC

9

Array Size

 Size = No. of Elements = n  UB = n - 1  Number of Bytes = size * Element size. All

elements are of the same size.

 Maximum size of 64 Kbytes.

int

249

float

25

250 elements = 500 bytes 26 elements = 104 bytes

slide-10
SLIDE 10
  • Prof. Amr Goneid, AUC

10

  • 3. How to Declare an Array

 Syntax:

<basetype> <name> [size] ; e.g. int a [20] ;

float x [101] ; const Maxelem = 200; typedef int itemtype; itemtype y [Maxelem+1]; string name [51]; enum color {red , green , blue}; color pixel [201]; int npixels[3];

slide-11
SLIDE 11
  • Prof. Amr Goneid, AUC

11

Sample Declarations

 Suppose

const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000;

slide-12
SLIDE 12
  • Prof. Amr Goneid, AUC

12

Sample Declarations

 Then the following are all correct array

declarations.

int A[10]; char B[MaxStringSize]; float C[M*N]; int Values[MaxListSize]; Rational D[N-15];

slide-13
SLIDE 13
  • Prof. Amr Goneid, AUC

13

  • 4. Operations on Arrays

 Declaration with Initialization:

e.g. int x [6] = {12 , 23 , 56 , 34 , 18 , 20}; char g[ ] = { ‘A’ , ‘B’ , ‘C’ ,’D’ , ‘F’ }; //This sets the size of the array g to 5 elements

slide-14
SLIDE 14
  • Prof. Amr Goneid, AUC

14

Operations on Arrays

 Accessing an Element:

<array name>[index] 0 =< index =< UB index (location of element in the array) can be a const, variable or any integral / ordinal expression. e.g. x[2] or y[i] or x[2*n+1]

slide-15
SLIDE 15
  • Prof. Amr Goneid, AUC

15 12

Operations on Arrays

 Index manipulation:

int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12;

slide-16
SLIDE 16
  • Prof. Amr Goneid, AUC

16 12

Operations on Arrays

Warning

 C++ will not flag an error if the array subscript

goes out of bounds

 Ex:

int B[10]; // declare B with 10 elements B[20] = 2; // subscript out of range This is allowed by the compiler, but will lead to unpredictable behavior

 Beware!

slide-17
SLIDE 17
  • Prof. Amr Goneid, AUC

17

Operations on Arrays

 Retrieve an element:

e.g. z = x[ i ] ;

 Update an element:

e.g. name[ i ] = “Ann” ; pixel[100] = red; npixels[green] ++ ;

 Input an element of an array:

cin >> x[i];

 Output an element of an array:

cout << x[i];

slide-18
SLIDE 18
  • Prof. Amr Goneid, AUC

18

  • 5. Passing to and from

Functions

 Passing an array element as a parameter:

e.g. void swap ( int &a , int &b); invoke as swap ( x[i] , x[j] ) ;

 Passing an entire array by reference:

e.g. int findmax ( int x [ ] , int size ); invoke as m = findmax ( x , n);

slide-19
SLIDE 19
  • Prof. Amr Goneid, AUC

19

Remember

 Arrays are always passed by reference  Can use const if array elements are not to

be modified, e.g.

int findmax ( const int x [ ] , int size );  You do not need to include the array size

within the brackets when defining an array parameter.

 This is because the array name is the base

address of the array, and the size is already known.

slide-20
SLIDE 20
  • Prof. Amr Goneid, AUC

20

  • 6. Examples

 A function to input n elements of an integer array and

return the array and n as parameters: const MAX_SIZE = 200; int a [MAX_SIZE]; void input_array ( int a[ ] , int &n ) { int n = 0; int v; while((n < MAX_SIZE) && (cin >> v)) { a[n] = v; n++; } }

slide-21
SLIDE 21
  • Prof. Amr Goneid, AUC

21

Examples

 A function that receives an integer array and

lists the first n elements of the array :

void output_array ( const int a[ ] , int n ) { for (int i = 0 ; i < n ; i++) cout << a[i] << “ “ ; cout << endl; }

slide-22
SLIDE 22
  • Prof. Amr Goneid, AUC

22

 A function to receive an integer array and return the

index of the minimum element in the sub-array starting at index (s) and ending at index (e): int index_of_min ( int a[ ] , int s , int e ) { int imin = s; for (int i = s+1; i <= e ; i++) if (a[i] < a[imin]) imin = i ; return imin ; }

Examples

slide-23
SLIDE 23
  • Prof. Amr Goneid, AUC

23

Examples

 A function to receive a real array and return the

average value of the elements. float average( float x[ ] , int n ) { float sum = 0; for (int i = 0; i < n ; i++) sum += x[i]; return (sum / float (n)) ; }

slide-24
SLIDE 24
  • Prof. Amr Goneid, AUC

24

  • 7. Example Functions

 Function1:

Computing the Average and Standard Deviation of a list of numbers.

 Function2:

Linear (Sequential) Search in an array.

 Function3:

Sorting an array using Selection Sort.

 Function4:

Sorting an array using Bubble Sort

 Function5:

Searching an array using Binary Search

slide-25
SLIDE 25
  • Prof. Amr Goneid, AUC

25

Function 1: Average & Standard Deviation

The average (av) of array x[0..n-1] is computed as the sum of all elements divided by n. The variance is defined as the average of the squared deviations from the average value. The Standard Deviation is the square root of the variance.

( )

v x x n v x n x

n i i n i i

= 〉 〈 − = = 〉 〈

∑ ∑

− = − =

σ , 1 , 1

2 1 1

slide-26
SLIDE 26
  • Prof. Amr Goneid, AUC

26

Function stat

void stat ( const float x[ ], int n, float &av, float &sd) { float d; float var = 0; av = average(x,n); for (int i = 0; i < n ; i++) { d = x[i] – av ; var += d*d; } sd = sqrt(var / float(n)); }

slide-27
SLIDE 27
  • Prof. Amr Goneid, AUC

27

Function 2: Linear Search

 The idea of a linear search is to walk

through the entire array until a target value is located. If found, its location is returned.

 If the target is not located some type

  • f indicator needs to be returned
slide-28
SLIDE 28
  • Prof. Amr Goneid, AUC

28

Linear Search Function

// Searches an integer array of size (n) // for a given element (the target) // Array elements ranging from 0 to // n - 1 are searched for an element // equal to target. // Returns the subscript of target if // found; otherwise, returns -1.

slide-29
SLIDE 29
  • Prof. Amr Goneid, AUC

29

linSearch Function (Cont.)

int linSearch (const int a[ ], int target, int n) { for (int i = 0; i < n; i++) if (a[i] == target) return i; // All elements were tested without success. return -1; } // end linSearch

slide-30
SLIDE 30
  • Prof. Amr Goneid, AUC

30

Function 3: Selection Sort

 Assume elements to be in locations 0..n-1  Let (i) be the start of a sub-array of at least

2 elements, i.e. i = 0 .. n-2

 for each i = 0 .. n-2

find smallest element in sub-array a[i] to a[n-1]. swap that element with that at the start

  • f the sub-array.
slide-31
SLIDE 31
  • Prof. Amr Goneid, AUC

31

How it works

4 3 1 6 2 5 1 3 4 6 2 5 1 2 4 6 3 5 1 2 3 4 6 5 1 2 3 6 4 5 1 2 3 4 5 6

slide-32
SLIDE 32
  • Prof. Amr Goneid, AUC

32

Selection Sort Algorithm

void selectsort (itemType a[ ], int n) { int i , j , m; for (i = 0; i < n-1; i++) { m = i ; for ( j = i+1; j < n; j++) if (a[j] < a[m]) m = j ; swap (a[i] , a[m]); } }

slide-33
SLIDE 33
  • Prof. Amr Goneid, AUC

33

Function 4: Bubble Sort

 The general idea is to compare adjacent elements

and swap if necessary

 Assume elements to be in locations 0..n-1  Let (i) be the index of the last element in a sub-

array of at least 2 elements, i.e. i = n-1 .. 1

slide-34
SLIDE 34
  • Prof. Amr Goneid, AUC

34

Bubble Sort Algorithm

 for each i = n-1…1

Compare adjacent elements aj and aj+1 , j = 0..i-1 and swap them if aj > aj+1 This will bubble the largest element in the sub-array a[0..i] to location (i).

slide-35
SLIDE 35
  • Prof. Amr Goneid, AUC

35

How it works

4 3 1 2 3 4 1 2 3 1 4 2 1 3 2 4 3 1 2 4 1 2 3 4

slide-36
SLIDE 36
  • Prof. Amr Goneid, AUC

36

Bubble Sort Algorithm

void bubbleSort (itemType a[ ], int n) { int i , j; bool swapped; for (i = n; --i >= 0; ) { swapped = false; for (j = 0; j < i; j++) { if (a[j] > a[j+1] ) { swap(a[j] , a[j+1]); swapped = true; } } if (!swapped) return; } }

slide-37
SLIDE 37
  • Prof. Amr Goneid, AUC

37

Function 5: Binary Search

slide-38
SLIDE 38
  • Prof. Amr Goneid, AUC

38

Binary Search: How it works

Assume elements in locations a[1]..a[n] to be already sorted in ascending order

 put the key (x) we are searching for in location a[0].  Set Low index L=1 and High index H=n  Let (m) be the index of the approximate middle between L and H  do

compute middle location (m) if (L > H) there is no hope to find (x) in the array, so set m = 0 else if x < a[m] discard a[m]..a[H] by setting H = m-1, else if x > a[m] discard a[1]..a[m] by setting L = m+1, else, x is found at a[m] while x is not yet found at a[m]

 return the location (m), if zero it is not found

slide-39
SLIDE 39
  • Prof. Amr Goneid, AUC

39

Binary Search Algorithm

int binsearch (itemType a[ ], int n, itemType x) { int L , m , H; a[0] = x; L = 1; H = n; do { m = (L + H)/2; if (L > H) m = 0; else if (x < a[m]) H = m-1; else L = m+1; } while (a[m] != x); return m; }

slide-40
SLIDE 40
  • Prof. Amr Goneid, AUC

40

2-D Arrays

slide-41
SLIDE 41
  • Prof. Amr Goneid, AUC

41

2-D Arrays

 Declaration & Indexing  2-D Arrays as Parameters  Simple Matrix Operations  Other Applications

slide-42
SLIDE 42
  • Prof. Amr Goneid, AUC

42

2-D Arrays

 Useful in representing a variety of data,

e.g. Tables, Matrices, Graphs and Images 35 32 33 34 31 31 29 28 28

City

Cairo Tanta Alex Day Fri Sat Sun

5 2 3 4 1 1 9 8 8

i j

A Table of Temp. A Matrix of Integers

slide-43
SLIDE 43
  • Prof. Amr Goneid, AUC

43

2-D Arrays

Bit Map Color Image

Zoomed showing Pixels

slide-44
SLIDE 44
  • Prof. Amr Goneid, AUC

44

Declaration & Indexing

 Declaration:

<element-type> <arrayName> [size 1][size2];

e.g.

double table[NROWS] [NCOLS];

 Indexing:

table[2] [4];

Row# 0 .. NROWS Column# 0 .. NCOLS

slide-45
SLIDE 45
  • Prof. Amr Goneid, AUC

45

Example

const int NRows = 11; const int Seats_In_Row = 9; string seatPlan [NRows][Seats_In_Row];

slide-46
SLIDE 46
  • Prof. Amr Goneid, AUC

46

Initialization

 We use nested loops with two-

dimensional arrays

const int NRows = 2; const int NCols = 3; float matrix[NRows][NCols] ={{5.0,4.5, 3.0}, {-16.0, -5.9, 0.0}};

slide-47
SLIDE 47
  • Prof. Amr Goneid, AUC

47

2-D Arrays as Parameters

 In 1-D arrays, it is not necessary to specify the size:

void display (int A[ ], int n); To follow the same convention with 2-D arrays: void display (int B[ ] [ ] , int n , int m);

 This will not work, because 2-D arrays are stored as

1-D arrays of arrays (1-D arrays of rows)

 Hence, beside the base address (name) we must

also specify the number of columns, e.g. void display (int B[ ][Ncol], int n, int m);

slide-48
SLIDE 48
  • Prof. Amr Goneid, AUC

48

SumArray.cpp

// FILE: SumArray.cpp // CALCULATES THE SUM OF THE ELEMENTS IN THE // FIRST rows ROWS OF AN ARRAY OF FLOATING POINT // VALUES WITH NCOLS (A CONSTANT) COLUMNS. // Pre: The type int constant NCOLS is // defined (NCOLS > 0) and the // array element values are defined and rows > 0. // Post: sum is the sum of all array element // values. // Returns: Sum of all values stored in the // array.

slide-49
SLIDE 49
  • Prof. Amr Goneid, AUC

49

SumArray.cpp

float sumArray (float a[ ][NCOLS], int rows) { float sum = 0.0; // Add each array element value to sum. for (int r = 0; r < rows; r++) for (int c = 0; c < NCOLS; c++) sum += a[r][c]; return sum; }

slide-50
SLIDE 50
  • Prof. Amr Goneid, AUC

50

Higher Dimensions

const int people = 10; const int years = 5; money sales[people][years][12];

slide-51
SLIDE 51
  • Prof. Amr Goneid, AUC

51

Simple Matrix Operations

 Matrix Addition  Matrix Transpose  Matrix Multiplication

slide-52
SLIDE 52
  • Prof. Amr Goneid, AUC

52

Matrix Addition

Given two matrices of the same dimensions Anm and Bnm. Their sum is a matrix of the same dimensions Cnm such that Cij = Aij + Bij

slide-53
SLIDE 53
  • Prof. Amr Goneid, AUC

53

Matrix Addition

// N , M are global constants void matAdd (float A[ ] [M] , float B[ ] [M] , float C[ ] [M]) { for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) C[i][j] = A[i][j] + B[i][j]; }

slide-54
SLIDE 54
  • Prof. Amr Goneid, AUC

54

Matrix Transpose

Given a matrix Anm , its transpose is AT = Bmn with elements Bji = Aij // N , M are global constants void matTranspose (float A[ ] [M] , float B[ ] [N]) { for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) B[j][i] = A[i][j] ; }

slide-55
SLIDE 55
  • Prof. Amr Goneid, AUC

55

Example:Matrix Multiplication

// Multiply matrix A(N rows x L columns) by matrix // B(L rows x M columns) to produce a matrix // C(N rows x M columns). // The elements of matrix C are: // C(i,j) = sum over k from 1 to L of {A(i,k) * B(k,j)} // with i = 1 to N , j = 1 to M // N , M , L are global constants

slide-56
SLIDE 56
  • Prof. Amr Goneid, AUC

56

Matrix Multiplication

void matMult (float A[ ] [L] , float B[ ] [M] , float C[ ] [M]) { for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { C[i][j] = 0; for (int k = 0; k < L; k++) C[i][j] += A[i][k] * B[k][j]; } }

slide-57
SLIDE 57
  • Prof. Amr Goneid, AUC

57

Image Application

 Image A has random gray levels between 0(Black) and

255(White). What is the algorithm used to convert Image A to the binary image B? Image A Image B

slide-58
SLIDE 58
  • Prof. Amr Goneid, AUC

58

Image Application

 Same algorithm would do this.

256 Gray Levels 2 Levels(Binary)

slide-59
SLIDE 59
  • Prof. Amr Goneid, AUC

59

Flip Left to Right

slide-60
SLIDE 60
  • Prof. Amr Goneid, AUC

60

Flip Upside Down

slide-61
SLIDE 61
  • Prof. Amr Goneid, AUC

61

Flip 90 Degrees to the Left