Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays.

Slides:



Advertisements
Similar presentations
Numeric Types & Ranges. ASCII Integral Type Numerical Inaccuracies Representational error – Round-off error – Caused by coding a real number as a finite.
Advertisements

One Dimensional Arrays
CHAPTER 10 ARRAYS II Applications and Extensions.
Data Structures Arrays and Structs Chapter The Array Data Type t Array elements have a common name –The array as a whole is referenced through.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Analysis & Design of Algorithms (CSCE 321)
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
Simple Arrays COMP104 Lecture 11 / Slide 2 Arrays * An array is a collection of data elements that are of the same type (e.g., a collection of integers,characters,
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Searching Arrays Linear search Binary search small arrays
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
Chapter 8 Arrays and Strings
CSE202: Lecture 16The Ohio State University1 Two Dimensional Arrays.
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Simple Arrays Programming COMP104 Lecture 12 / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g., a collection.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CS1061 C Programmuing Lecture 12 Arrays A. O’Riordan, 2004.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
Matrices Jordi Cortadella Department of Computer Science.
Chapter 8 Arrays and Strings
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 3. Selection Constructs.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
Arrays Why we need data structure? Simple data types use a single memory cell to store a variable. Sometimes (for example scores of a class) it is more.
Two-Dimensional Arrays ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
More Array Access Examples Here is an example showing array access logic: const int MAXSTUDENTS = 100; int Test[MAXSTUDENTS]; int numStudents = 0;... //
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part 1. Complexity Bounds.
Introduction to Programming (in C++) Multi-dimensional vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part 3. Time Complexity Calculations.
Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 3. Introduction to the Analysis of Algorithms.
Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 8a. Sorting(1): Elementary Algorithms.
Computer Skills2 / Scientific Colleges 1 Arrays Topics to cover: Arrays Data Types One-dimensional Arrays Two-dimensional Arrays.
Consultation Hours. Mubashir: – Tuesday from 12:30 to 1:30 with ease of Students. Zohaib – Wednesday b/w 9:30 -10:30 Location: TA Room (next to HOD Office)
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
CSCE 210 Data Structures and Algorithms
CSCE 210 Data Structures and Algorithms
Basic Array Definition
CSCE 210 Data Structures and Algorithms
Array Data Structure Chapter 6
Array Data Structure B.Ramamurthy 11/21/2018 B.Ramamurthy.
Arrays Topics to cover: Arrays Data Types One-dimensional Arrays
Chapter 9: Data Structures: Arrays
Array Data Structure Chapter 6
COMS 261 Computer Science I
Presentation transcript:

Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

Prof. Amr Goneid, AUC2 Arrays

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

Prof. Amr Goneid, AUC4 1. Data Structures Data SetLinearTreeGraph

Prof. Amr Goneid, AUC5 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.

Prof. Amr Goneid, AUC6 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

Prof. Amr Goneid, AUC7 1-D Arrays

Prof. Amr Goneid, AUC8 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) 0n -1 index

Prof. Amr Goneid, AUC9 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 0249 float elements = 500 bytes 26 elements = 104 bytes

Prof. Amr Goneid, AUC10 3. How to Declare an Array Syntax: [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];

Prof. Amr Goneid, AUC11 Sample Declarations Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000;

Prof. Amr Goneid, AUC12 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];

Prof. Amr Goneid, AUC13 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

Prof. Amr Goneid, AUC14 Operations on Arrays Accessing an Element: [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]

Prof. Amr Goneid, AUC15 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;

Prof. Amr Goneid, AUC16 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!

Prof. Amr Goneid, AUC17 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];

Prof. Amr Goneid, AUC18 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);

Prof. Amr Goneid, AUC19 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.

Prof. Amr Goneid, AUC20 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 > v)) { a[n] = v;n++; } }

Prof. Amr Goneid, AUC21 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; }

Prof. Amr Goneid, AUC22 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

Prof. Amr Goneid, AUC23 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)) ; }

Prof. Amr Goneid, AUC24 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

Prof. Amr Goneid, AUC25 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.

Prof. Amr Goneid, AUC26 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)); }

Prof. Amr Goneid, AUC27 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 of indicator needs to be returned

Prof. Amr Goneid, AUC28 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.

Prof. Amr Goneid, AUC29 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

Prof. Amr Goneid, AUC30 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 of the sub-array.

Prof. Amr Goneid, AUC31 How it works

Prof. Amr Goneid, AUC32 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]); }

Prof. Amr Goneid, AUC33 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

Prof. Amr Goneid, AUC34 Bubble Sort Algorithm for each i = n-1…1 Compare adjacent elements a j and a j+1, j = 0..i-1 and swap them if a j > a j+1 This will bubble the largest element in the sub-array a[0..i] to location (i).

Prof. Amr Goneid, AUC35 How it works

Prof. Amr Goneid, AUC36 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; }

Prof. Amr Goneid, AUC37 Function 5: Binary Search

Prof. Amr Goneid, AUC38 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

Prof. Amr Goneid, AUC39 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; }

Prof. Amr Goneid, AUC40 2-D Arrays

Prof. Amr Goneid, AUC41 2-D Arrays Declaration & Indexing 2-D Arrays as Parameters Simple Matrix Operations Other Applications

Prof. Amr Goneid, AUC42 2-D Arrays Useful in representing a variety of data, e.g. Tables, Matrices, Graphs and Images City Cairo Tanta Alex DayFriSatSun i j A Table of Temp. A Matrix of Integers

Prof. Amr Goneid, AUC43 2-D Arrays Bit MapColor Image Zoomed showing Pixels

Prof. Amr Goneid, AUC44 Declaration & Indexing Declaration: [size 1][size2]; e.g. double table[NROWS] [NCOLS]; Indexing: table[2] [4]; Row# 0.. NROWS Column# 0.. NCOLS

Prof. Amr Goneid, AUC45 Example const int NRows = 11; const int Seats_In_Row = 9; string seatPlan [NRows][Seats_In_Row];

Prof. Amr Goneid, AUC46 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}};

Prof. Amr Goneid, AUC47 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);

Prof. Amr Goneid, AUC48 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.

Prof. Amr Goneid, AUC49 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; }

Prof. Amr Goneid, AUC50 Higher Dimensions const int people = 10; const int years = 5; money sales[people][years][12];

Prof. Amr Goneid, AUC51 Simple Matrix Operations Matrix Addition Matrix Transpose Matrix Multiplication

Prof. Amr Goneid, AUC52 Matrix Addition Given two matrices of the same dimensions A nm and B nm. Their sum is a matrix of the same dimensions C nm such that C ij = A ij + B ij

Prof. Amr Goneid, AUC53 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]; }

Prof. Amr Goneid, AUC54 Matrix Transpose Given a matrix A nm, its transpose is A T = B mn with elements B ji = A ij // 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] ; }

Prof. Amr Goneid, AUC55 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

Prof. Amr Goneid, AUC56 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]; }

Prof. Amr Goneid, AUC57 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 AImage B

Prof. Amr Goneid, AUC58 Image Application Same algorithm would do this. 256 Gray Levels2 Levels(Binary)

Prof. Amr Goneid, AUC59 Flip Left to Right

Prof. Amr Goneid, AUC60 Flip Upside Down

Prof. Amr Goneid, AUC61 Flip 90 Degrees to the Left