CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

Similar documents
9.1 The Array Data Type. Data Structures Arrays and Structs. Arrays. Arrays. Array Declaration. Arrays. Array elements have a common name

CSCE 110 PROGRAMMING FUNDAMENTALS

Computer Science & Engineering 150A Problem Solving Using Computers

Matrices. Jordi Cortadella Department of Computer Science

CSCE 110 PROGRAMMING FUNDAMENTALS

Arrays. Week 4. Assylbek Jumagaliyev

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion (Solutions)

Lab #10 Multi-dimensional Arrays

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Introduction to Computer Science Midterm 3 Fall, Points

C++ PROGRAMMING SKILLS Part 4: Arrays

BITG 1113: Array (Part 1) LECTURE 8

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

Arrays. Arrays are of 3 types One dimensional array Two dimensional array Multidimensional array

CS 261 Data Structures. Big-Oh Analysis: A Review

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Lecture 6 Sorting and Searching

Review of Important Topics in CS1600. Functions Arrays C-strings

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

CSCE 110 PROGRAMMING FUNDAMENTALS

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

Algorithm Complexity Analysis: Big-O Notation (Chapter 10.4) Dr. Yingwu Zhu

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Chapter 01 Arrays Prepared By: Dr. Murad Magableh 2013

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion

Matrix Multiplication

Chapter 10 - Notes Applications of Arrays

Arrays. Systems Programming Concepts

Matrix Multiplication

Chapter 7 Array. Array. C++, How to Program

Principles of Programming. Chapter 6: Arrays

Data Structures and Algorithms for Engineers

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Objectives of This Chapter

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

How to declare an array in C?

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Solutions to Chapter 8

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Introduction to Arrays

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Creating a C++ Program

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

Lecture 2. Two-Dimensional Arrays

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

Fundamental of Programming (C)

One Dimension Arrays 1

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Problem Solving: Storyboards for User Interaction

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

CSCE 110 Notes on Recursive Algorithms (Part 12) Prof. Amr Goneid

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

Columns A[0] A[0][0] = 20 A[0][1] = 30

Arrays and Applications

Programming 1. Lecture 6 Structured data types. Arrays

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities

Outline. Arrays. Function Arguments. Arrays. Adding Two Arrays /* */ /* This program adds 2 arrays */ ELEC 330 1

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

CS242 COMPUTER PROGRAMMING

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #04

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Programming. C++ Basics

CS2141 Software Development using C/C++ C++ Basics

Arrays, Vectors Searching, Sorting

Arrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept

C/C++ Programming Lecture 18 Name:

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

LECTURE 17. Array Searching and Sorting

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

ARRAYS(II Unit Part II)

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

CS Spring 05 - MidTerm

Short Notes of CS201

Lecture 04 FUNCTIONS AND ARRAYS

Chapter4: Data Structures. Data: It is a collection of raw facts that has implicit meaning.

CSCE 110 PROGRAMMING FUNDAMENTALS

Why arrays? To group distinct variables of the same type under a single name.

Chapter 6 part 1. Data Types. (updated based on 11th edition) ISBN

CS201 - Introduction to Programming Glossary By

CSE030 Fall 2012 Final Exam Friday, December 14, PM

Linear Search. Sorting Algorithms. linear search code. Sorting in Ascending Order Selection Sort. Selection sort algorithm

Two common problems in processing arrays. Examples. Algorithm for searching over a sorted array is much more efficient than over an unsorted array.

Transcription:

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 Operations on Arrays Passing to and from Functions Examples Example Functions Prof. Amr Goneid, AUC 3

1. Data Structures Data Set Linear Tree Graph Prof. Amr Goneid, AUC 4

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, AUC 5

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, AUC 6

1-D Arrays Prof. Amr Goneid, AUC 7

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

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. 0 250 elements = 500 bytes 249 int 0 26 elements = 104 bytes 25 float Prof. Amr Goneid, AUC 9

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

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

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, AUC 12

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, AUC 13

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] Prof. Amr Goneid, AUC 14

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, AUC 12 15

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, AUC 12 16

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, AUC 17

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, AUC 18

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, AUC 19

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++; } } Prof. Amr Goneid, AUC 20

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, AUC 21

Examples 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 ; } Prof. Amr Goneid, AUC 22

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, AUC 23

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, AUC 24

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. n 1 n 1 1 1 x = xi, v = i = n n i= 0 i= 0 2 ( x x ), σ v Prof. Amr Goneid, AUC 25

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, AUC 26

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, AUC 27

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, AUC 28

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, AUC 29

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, AUC 30

How it works 4 3 1 6 2 5 1 3 4 6 2 5 1 2 4 6 3 5 1 2 3 6 4 5 1 2 3 4 6 5 1 2 3 4 5 6 Prof. Amr Goneid, AUC 31

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, AUC 32

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 subarray of at least 2 elements, i.e. i = n-1.. 1 Prof. Amr Goneid, AUC 33

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, AUC 34

How it works 4 3 1 2 3 4 1 2 3 1 4 2 3 1 2 4 1 3 2 4 1 2 3 4 Prof. Amr Goneid, AUC 35

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, AUC 36

Function 5: Binary Search Prof. Amr Goneid, AUC 37

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, AUC 38

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, AUC 39

2-D Arrays Prof. Amr Goneid, AUC 40

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

2-D Arrays Useful in representing a variety of data, e.g. Tables, Matrices, Graphs and Images Day Fri Sat Sun j City Cairo 35 32 33 i 5 2 3 Tanta 34 31 31 4 1 1 Alex 29 28 28 9 8 8 A Table of Temp. A Matrix of Integers Prof. Amr Goneid, AUC 42

2-D Arrays Bit Map Color Image Zoomed showing Pixels Prof. Amr Goneid, AUC 43

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

Example const int NRows = 11; const int Seats_In_Row = 9; string seatplan [NRows][Seats_In_Row]; Prof. Amr Goneid, AUC 45

Initialization const int NRows = 2; const int NCols = 3; float matrix[nrows][ncols] ={{5.0,4.5, 3.0}, {-16.0, -5.9, 0.0}}; We use nested loops with twodimensional arrays Prof. Amr Goneid, AUC 46

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, AUC 47

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, AUC 48

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, AUC 49

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

Simple Matrix Operations Matrix Addition Matrix Transpose Matrix Multiplication Prof. Amr Goneid, AUC 51

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, AUC 52

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, AUC 53

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, AUC 54

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, AUC 55

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, AUC 56

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

Image Application Same algorithm would do this. 256 Gray Levels 2 Levels(Binary) Prof. Amr Goneid, AUC 58

Flip Left to Right Prof. Amr Goneid, AUC 59

Flip Upside Down Prof. Amr Goneid, AUC 60

Flip 90 Degrees to the Left Prof. Amr Goneid, AUC 61