2.2 The array as an ADT

Size: px
Start display at page:

Download "2.2 The array as an ADT"

Transcription

1 2.2 The array as an ADT Chapter 2: Arrays Hsien-Chou Liao Depart. of Comp. Sci. and Info. Eng. Chaoyang Univ. of Tech. Many programmers view an array only as a consecutive set of memory locations. Is array defined as an ADT? Array is a set of pairs, <index, value> Also called correspondence or mapping 1 3 ADT (Abstract Data Type): NaturalNumber ADT NaturalNumber is objects: An ordered subrange of the integers starting at zero and ending at the maximum integer (MAXINT) on the computer. functions: for all x, y NaturalNumber; TRUE, FALSE Boolean and where +,,<,==, and = are the usual integer operations Zero(): NaturalNumber ::= IsZero(x): Boolean ::= if (x==) IsZero = TRUE else IsZero = FALSE Add(x, y): NaturalNumber ::= if (x+y<=maxint) Add = x + y Equal(x, y): Boolean else Add = MAXINT ::= if (x == y) Equal = true else Equal = false Successor(x): NaturalNumber::= if (x == MAXINT) Successor = x else Successor = x + 1 Subtract(x, y): NaturalNumber::= if (x < y) Subtract = else Subtract = x y end NaturalNumber ADT GeneralArray class GeneralArray // A set of pairs <index, value> public: GeneralArray(int j, RangeList list, float initvalue = defaultvalue); // constructor // j: dimension float Retrieve(index i); // return the float associated with i void Store(index i, float x); // replace the old value associate with i ; 2 4

2 Array 2.3 Polynomial ADT char A[3][4]; 1 2 logical structure A[2][1] Mapping: A[i][j]=A[][]+i*4+j // row-major physical structure A[][] A[][1] A[][2] A[][3] A[1][] A[1][1] A[1][2] A[1][3] Array can also be used to implement other ADT. Ordered (linear) list: for example: Days of the week (Sunday, Monday, ) Values in a deck of cards: (Ace, 2, 3, 4, ) Floors of a building 5 7 The Operations on 1-dim Array Store Replace the <index, oldvalue> pair with the <index, newvalue> pair. A[3] = 45 A Here is a problem requiring ordered list: Polynomial: a(x) = 3x 2 + 2x - 4 b(x) = x 8 1x 5-3x Coefficients and exponents a(x) is 3, 2, -4 and 2, 1, b(x) is 1, -1, -3, 1 and 8, 5, 3, 6 8

3 Polynomial Addition ADT: Polynomial class Polynomial // p(x) is a set of order pairs of <e i,a i > // where a i is a nonzero float coefficient and e i is a non-negative integer exponent. public: Polynomial( ); // Construct the polynomial p(x) = Polynomial Add(Polynomial poly); // return the sum of *this and poly Polynomial Mult(Polynomial poly); // return the product of *this and poly float Eval(float f ); // Evaluate the polynomial *this at f and return the result. ; a.termarray[].coef a.termarray[].exp Assume Representation 3 is used: Add the following two polynomials: a(x) = 2x b(x) = x 4 + 1x 3 + 3x c.termarray[].coef b.termarray[].coef b.termarray[].exp c.termarray[].exp Polynomial Representations Some representation decisions: Representation 1 int degree; // degree MaxDegree float coef [MaxDegree + 1]; Representation 2 int degree; float *coef; Polynomial::Polynomial(int d) degree = d; coef = new float [degree+1]; Representation 3 class Polynomial; // forward declaration class Term friend Polynomial; float coef; int exp; ; // coefficient // exponent term *termarray; int capacity; // size of termarray int terms; // number of nonzero terms C++ Program Program 2.8: The Add function Time complexity: O(m+n) Program 2.9: Adding a new term void Polynomial::NewTerm(const float thecoeff, const int theexp) // Add a new term to the end of termarray if (terms = = capacity) // double the capacity of termarray capacity *= 2; term *temp = new term[capacity]; // new array copy(termarray, termarray + terms, temp); delete [] termarray ; // deallocate old memory termarray = temp; termarray [terms].coef = thecoeff; termarray [terms++].exp = theexp; 1 12

4 2.4 Sparse Matrices ADT SparseMatrix A matrix is a mathematical object that arises in many physical problems. It is natural to store a matrix in a two-dimensional array, a[m][n]. For example: (sparse matrix) Q: What is the problem to represent a sparse matrix in a[m][n]? 13 class SparseMatrix public: SparseMatrix(int r, int c,int t); // constructor SparseMatrix Transpose( ); //returns the SparseMatrix obtained by interchanging the row and column value SparseMatrix Add(SparseMatrix b); // SparseMatrix Multiply(SparseMatrix b); // ; 15 Sparse Matrix Representation Sparse Matrix Representation (Cont.) Use triple <row, column, value> Store triples row by row For all triples within a row, their column indices are in ascending order. To ensure that the operations terminate: Must know the number of rows and columns and the number of nonzero elements The class definition: (a) Sparse matrix stored as triples (b) The transpose class SparseMatrix class MatrixTerm friend class SparseMatrix int row, col, value; ; int rows, cols, terms, capacity; MatrixTerm *smarray; 14 16

5 Transposing a Matrix Intuitive way: for (each row i) take element (i, j, value) and store it in (j, i, value) of the transpose Q: What is the difficulty of the above way? It cannot know the place of an element in the transpose. More efficient way: for (all elements in column j) place element (i, j, value) in position (j, i, value) Please see the example in the previous slide. 17 Fast Matrix Transpose If matrix is represented in 2-dim arrays. The time complexity is O(rows cols). To sort terms is of the order of rows cols, the time complexity is O(rows cols). Therefore, O(terms cols) becomes O(rows cols 2 ). O(rows cols 2 ) is worse than O(rows cols), what does it means? Conserve space but trading away too much time. A fast transpose function in Program Determine the number of elements in each column. It gives the number of element in each row of b Obtain the starting point of each row of b. Move the elements of a one by one into correct position in b. Q: Time complexity? 19 Program 2.1: Transposing a Matrix SparseMatrix SparseMatrix::Transpose( ) // return the transpose of *this SparseMatrix b(cols, rows, terms); // capacity of b.smarray is terms if (terms > ) // nonzero matrix int currentb = ; for (int c = ; c < cols ; c++) // transpose by columns for (int i = ; i < terms ; i++) // find and move terms in column c if (smarray[i].col = = c) b.smarray[currentb].row = c; b.smarray[currentb].col = smarray[i].row; b.smarray[currentb++].value = smarray[i].value; // end of if (terms > ) return b; Q: Time complexity? 18 Program 2.11 Fast Matrix Transposing SparseMatrix SparseMatrix::FastTranspose( ) SparseMatrix b(cols, rows, terms); if (terms > ) int *rowsize = new int[cols]; int *rowstart = new int[cols]; fill(rowsize, rowsize + cols, ); for (int i = ; i < terms ; i ++) rowsize[smarray[i].col]++; O(terms) rowstart[] = ; for (int i = 1 ; i < cols ; i++) rowstart[i] = rowstart[i-1] + rowsize[i-1]; O(cols-1) for (int i = ; i < terms ; i++) O(terms) int j = rowstart[smarray[i].col]; b.smarray[j].row= smarray[i].col; b.smarray[j].col = smarray[i].row; b.smarray[j].value = smarray[i].value; rowstart[smarray[i].col]++; delete [] rowsize; delete [] rowstart; return b; Overall complexity is O(cols + terms) 2

6 Time complexity of FastTranspose Is really only O(cols + terms)? To sort terms is of the order of rows cols, the time complexity is O(rows cols). Therefore, O(cols + terms) becomes O(rows cols). It is the same as when 2-dim arrays are in use. Two Dimensional Array Row Major Order Figure 2.6: row row 1 row u 1-1 u 2 elements u 2 elements col col 1 col 2 col u 2-1 X X X X X X X X X X X X row row 1 row i row u 1-1 i * u 2 element Representation of Arrays Multidimensional arrays are usually implemented by one dimensional array via either row major order or column major order. Example: one dimensional array α: the address of a[] α α+1 α+2 α+3 α+4 α+5 α+6 α+7 α+8 α+9 α+1 α+12 a[] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[1] a[11] The address of elements in 2-dim array For a two-dim array, A[r][c], assume every element occupies len bytes and the address of the first element is α. The array is stored in row major order. Therefore, The address of A[][3] is α+3*len The address of A[3][] is α+(3*c+)*len... The address of A[m][n] is α+(m* c + n)*len 22 24

7 2.6 The String ADT A string is defined as the form: S=s, s 1,, s i, where s i are characters. H e l l o W o r l d \ Operations: Create a new empty string Reading a string or printing it out Concatenation: Appending two string together Copying a string 25 String pattern matching Two string, s and pat, where pat is a pattern to be searched for in s. s.find(pat): return an index i, or return -1 The easiest but least efficient method: int String::Find(String pat) for (int start = ; start <= Length( )-pat.length(); star ++) int j; for (j = ; j < pat.length( ) && str [start+j] = = pat.str[j]; j++) if (j = = pat.length( )) return start; // match found // no match at position start return -1 ; // pat is empty or does not occur in s Q: Time complexity? O(lengthP lengths) 27 Abstract data type String String Matching: The Knuth-Morris-Pratt Algorithm class String public: String(char *init, int m); // Constructor bool operator = = (String t); // if the string represented by *this equals t, return true; else return false. bool operator!( ); // If *this is empty then return true; else return false. int Length( ); // Return the number of characters in *this. String Concat(String t); // Return a string whose elements are those of *this followed by those of t. String Substr(int i, int j); // Return a string containing the j characters of *this at positions i, i+1,..., i+j 1 // if there are valid positions of *this; otherwise, throw an exception. int Find(String pat); // Return an index i such that pat match the substring of *this that begins // at position i. Return 1 if pat is either empty or not a substring of*this 26 Definition: If p = p p 1 p n-1 is a pattern, then its failure function, f, is defined as f ( j) largest k < j such that p... pk = p j k... p j if such a k exists = 1 otherwise If a partial match is found such that s i-j s i-1 = p p 1 p j-1 and s i p j then matching may be resumed by comparing s i and p f(j 1)+1 if j. If j =, then we may continue by comparing s i+1 and p. 28

8 Fast Matching Example 1 Suppose exists a string s and a pattern pat = abcabcacab, let s try to match pattern pat in string s. Failure function is shown below: j pat a b c a b c a c a b f for j=, since k < j, therefore f()=-1 for j=1, k=, p =a p 1 =b, therefore f(1)=-1 for j=4, k=, a b k=1, a b = a b k=2, a b c c a b k=3, a b c a b c a b, therefore f(4)=1 Fast Matching Example 2 Failure function is shown below: j pat a b c a b c a c a b f s = - a b c a b c a?.? pat = a b c a b c a c a b j = 7, f (j-1) + 1 = = 4 a b c a b c a c a b New start matching point Fast Matching Example 1 Suppose exists a string s and a pattern pat = abcabcacab, let s try to match pattern pat in string s. Failure function is shown below: j pat a b c a b c a c a b f s = - a b c a??...? pat = a b c a b c a c a b j = 4, f (j-1)+1 = 1 a b c a b c a c a b Easier Matching for Example 2 Failure function is shown below: j pat a b c a b c a c a b f s = - a b c a b c a?.? pat = a b c a b c a c a b a.. a.. a b c a b.. The above matching can be skipped using the fast matching method. New start matching point 3 32

9 Pattern-matching with failure function 1 int String::FastFind(String pat) 2 //Determine if pat is a substring of s 3 int posp =, poss = ; 4 int lengthp = pat.length(), lengths = Length(); 5 while((posp < lengthp) && (poss < lengths)) 6 if (pat.str[posp] = = str[poss]) // character match 7 posp++; poss++; 8 9 else 1 if (posp = = ) 11 poss++; 12 else posp = pat. f [posp-1] + 1; 13 if (posp < lengthp) return 1; 14 else return poss-lengthp; 15 Thanks for your attention! Q & A Q: Time complexity? 33 Computing the failure function 1 void String::FailureFunction() 2 // Compute the failure function for the pattern *this 3 int lengthp = Length( ); 4 f[] = -1; 5 for (int j = 1; j < lengthp; j++) // compute f [j] 6 7 int i = f [j-1]; 8 while ((*(str+j)!= *(str+i+1)) && (i >= )) i = f [i]; 9 if (*(str+j) = = *(str+i+1)) 1 f [j] = i+1; 11 else f [j] = -1; Q: Time complexity of computing failure function? Q: The total time complexity of FastFind? 34

Arrays. 2.2 The Array as an Abstract Data Type. Array:

Arrays. 2.2 The Array as an Abstract Data Type. Array: Arrays 2.2 The Array as an Abstract Data Type Array: A set of pairs: (correspondence or mapping) Two operations: retrieve, store Now we will use the C++ class to define an ADT. 1 GeneralArray

More information

Arrays. Example: int list[5]: list[0],, list[4] each contains an integer. List

Arrays. Example: int list[5]: list[0],, list[4] each contains an integer. List Arrays Arrays Array: a set of index and value data structure For each index, there is a value associated with that index. representation (possible) implemented by using consecutive memory. Example: int

More information

2.1.5 Miscellaneous Topics

2.1.5 Miscellaneous Topics 2.1.5 Miscellaneous Topics struct definition of a data type union not specify whether a given member has public, private, protected no way to know what the data type is until runtime static class data

More information

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.

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. Data Structures Introduction 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. Representation of a large number of homogeneous

More information

How to declare an array in C?

How to declare an array in C? Introduction 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. Representation of a large number of homogeneous values.

More information

The string Class. Lecture 21 Sections 2.9, 3.9, Robb T. Koether. Wed, Oct 17, Hampden-Sydney College

The string Class. Lecture 21 Sections 2.9, 3.9, Robb T. Koether. Wed, Oct 17, Hampden-Sydney College The string Class Lecture 21 Sections 2.9, 3.9, 3.10 Robb T. Koether Hampden-Sydney College Wed, Oct 17, 2018 Robb T. Koether (Hampden-Sydney College) The string Class Wed, Oct 17, 2018 1 / 18 1 The String

More information

1.1 Basic Concepts 1

1.1 Basic Concepts 1 1.1 Basic Concepts 1 What is Data Structure? (1) Data Structure How do we store (input/output) data in a (mostly) main memory? Ex) How to store a Matrix in a memory? We need to specify a data structure

More information

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

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example: Collecting Elements How to collect elements of the same type? Eg:., marks on assignments: APS105 Arrays Textbook Chapters 6.1-6.3 Assn# 1 2 3 4 5 6 Mark 87 89 77 96 87 79 Eg: a solution in math: x 1, x

More information

8 Basic Concepts 1.3 ALGORITHM SPECIFICATION Introduction

8 Basic Concepts 1.3 ALGORITHM SPECIFICATION Introduction 8 Basic Concepts as a pointer. This has proven to be a dangerous practice on some computers and the programmer is urged to define explicit return types for functions. 1.3 ALGORITHM SPECIFICATION 1.3.1

More information

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos. UNIT 2 ARRAYS Arrays Structure Page Nos. 2.0 Introduction 23 2.1 Objectives 24 2.2 Arrays and Pointers 24 2.3 Sparse Matrices 25 2.4 Polynomials 28 2.5 Representation of Arrays 30 2.5.1 Row Major Representation

More information

Classic Data Structures Introduction UNIT I

Classic Data Structures Introduction UNIT I ALGORITHM SPECIFICATION An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. All algorithms must satisfy the following criteria: Input. An algorithm has zero

More information

Chapter 2 Arrays and Structures

Chapter 2 Arrays and Structures Data Structure Chapter 2 Arrays and Structures Angela Chih-Wei Tang Department of Communication Engineering National Central University Jhongli, Taiwan 2 Spring Outline Array Structures Polynomial Sparse

More information

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues By: Pramod Parajuli, Department of Computer Science, St. Xavier

More information

Matrices. Jordi Cortadella Department of Computer Science

Matrices. Jordi Cortadella Department of Computer Science Matrices Jordi Cortadella Department of Computer Science Matrices A matrix can be considered a two-dimensional vector, i.e. a vector of vectors. my_matrix: 3 8 1 0 5 0 6 3 7 2 9 4 // Declaration of a matrix

More information

Monday, October 24, 2016

Monday, October 24, 2016 Monday, October 24, 2016 Topics for today Arrays and Indexed Addressing Arrays as parameters of functions Multi-dimensional arrays Option A: Space-minimal solution Option B: Iliffe vectors Array bound

More information

Classification s of Data Structures

Classification s of Data Structures Linear Data Structures using Sequential organization Classification s of Data Structures Types of Data Structures Arrays Declaration of arrays type arrayname [ arraysize ]; Ex-double balance[10]; Arrays

More information

國立清華大學電機工程學系. Outline

國立清華大學電機工程學系. Outline 國立清華大學電機工程學系 EE2410 Data Structure Chapter 4 Linked List (Part II) Outline Equivalence Class Sparse Matrices Doubly Linked Lists Generalized Lists Virtual Functions and Dynamic Binding ch4.2-2 1 Equivalence

More information

A string is a sequence of characters. In the field of computer science, we use strings more often as we use numbers.

A string is a sequence of characters. In the field of computer science, we use strings more often as we use numbers. STRING ALGORITHMS : Introduction A string is a sequence of characters. In the field of computer science, we use strings more often as we use numbers. There are many functions those can be applied on strings.

More information

Fall, 2015 Prof. Jungkeun Park

Fall, 2015 Prof. Jungkeun Park Data Structures t and Algorithms Circular lists / Doubly linked lists Fall, 2015 Prof. Jungkeun Park Copyright Notice: This material is modified version of the lecture slides by Prof. Rada Mihalcea in

More information

Advantage of an array ADT:

Advantage of an array ADT: Data Structures using C Chapter-2 ARRAYS AND SRUCTURES Array an array is a set of pairs, , such that each index that is defined has a value associated with it a consecutive set of memory

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

Functions. Arash Rafiey. September 26, 2017

Functions. Arash Rafiey. September 26, 2017 September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic

More information

Datatypes, Variables, and Operations

Datatypes, Variables, and Operations Datatypes, Variables, and Operations 1 Primitive Type Classification 2 Numerical Data Types Name Range Storage Size byte 2 7 to 2 7 1 (-128 to 127) 8-bit signed short 2 15 to 2 15 1 (-32768 to 32767) 16-bit

More information

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer.

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer. C++ - Lesson 2 1. Explain the following declarations: a) int *a(int a[]); This is a function prototype. 'a' is a function that takes an integer array argument and returns an integer pointer. b) const char

More information

Abstract Data Type array. 1D Array Representation In C++ Space Overhead. Data Structures and Programming 資料結構與程式設計. Topic 5 Arrays and Matrices

Abstract Data Type array. 1D Array Representation In C++ Space Overhead. Data Structures and Programming 資料結構與程式設計. Topic 5 Arrays and Matrices Data Structures and Programming 資料結構與程式設計 Topic 5 Arrays and Matrices 課程編號 :901 31900 EE 3011 科目名稱 : 資料結構與程式設計授課教師 : 黃鼎偉時間地點 : 一 678 電機二館 229 Abstract Data Type array Abstract Data Type (ADT) AbstractDataType

More information

CHAPTER 4 LINKED LISTS

CHAPTER 4 LINKED LISTS CHAPTER 4 LINKED LISTS Iris Hui-Ru Jiang Fall 2008 2 Contents Array vs. list Singly linked lists Doubly linked lists Applications Readings Chapter 4 C++ STL list iterators iterator, const_iterator reverse_iterator,

More information

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305 Q.1 If h is any hashing function and is used to hash n keys in to a table of size m, where n

More information

MODULE 3: LINKED LIST

MODULE 3: LINKED LIST MODULE 3: LINKED LIST DEFINITION A linked list, or one-way list, is a linear collection of data elements, called nodes, where the linear order is given by means of pointers. That is, each node is divided

More information

Data Structures CHAPTER 1 1

Data Structures CHAPTER 1 1 Data Structures CHAPTER 1 1 Books Fundamentals of Data Structures in C, 2nd Edition. ( 開發圖書,(02) 8242-3988) Administration Instructor: 曾學文資工系副教授 Office: Room 908 Email: hwtseng@nchu.edu.tw Tel: 04-22840497

More information

MA 511: Computer Programming Lecture 3: Partha Sarathi Mandal

MA 511: Computer Programming Lecture 3: Partha Sarathi Mandal MA 511: Computer Programming Lecture 3: http://www.iitg.ernet.in/psm/indexing_ma511/y10/index.html Partha Sarathi Mandal psm@iitg.ernet.ac.in Dept. of Mathematics, IIT Guwahati Semester 1, 2010-11 Last

More information

Hashing. Manolis Koubarakis. Data Structures and Programming Techniques

Hashing. Manolis Koubarakis. Data Structures and Programming Techniques Hashing Manolis Koubarakis 1 The Symbol Table ADT A symbol table T is an abstract storage that contains table entries that are either empty or are pairs of the form (K, I) where K is a key and I is some

More information

TWO DIMENSIONAL ARRAY OR MATRIX common name scores Defined as scores[10][5] IE 10 rows x 5 columns showing name of each position; some values below

TWO DIMENSIONAL ARRAY OR MATRIX common name scores Defined as scores[10][5] IE 10 rows x 5 columns showing name of each position; some values below TWO DIMENSIONAL ARRAY OR MATRIX common name scores Defined as scores[10][5] IE 10 rows x 5 columns showing name of each position; some values below Values in the memory could be scores[1][2]=78 scores[0][2]=56

More information

Wednesday, March 14, 2018

Wednesday, March 14, 2018 Wednesday, March 14, 2018 Topics for today Arrays and Indexed Addressing Arrays as parameters of functions Multi-dimensional arrays Option A: Space-minimal solution Option B: Iliffe vectors Array bound

More information

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A

More information

Lesson:9 Working with Array and String

Lesson:9 Working with Array and String Introduction to Array: Lesson:9 Working with Array and String An Array is a variable representing a collection of homogeneous type of elements. Arrays are useful to represent vector, matrix and other multi-dimensional

More information

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

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #04 Department of Computer Science & Engineering Indian Institute of Technology Kharagpur Topic: Arrays and Strings Practice Sheet #04 Date: 24-01-2017 Instructions: For the questions consisting code segments,

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

More About Factoring Trinomials

More About Factoring Trinomials Section 6.3 More About Factoring Trinomials 239 83. x 2 17x 70 x 7 x 10 Width of rectangle: Length of rectangle: x 7 x 10 Width of shaded region: 7 Length of shaded region: x 10 x 10 Area of shaded region:

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake Assigning Values // Example 2.3(Mathematical operations in C++) float a; cout > a; cout

More information

Do not write in this area A.1 A.2 A.3 A.4 A.5 A.6 B.1 B.2 B.3 TOTAL. Maximum possible points:

Do not write in this area A.1 A.2 A.3 A.4 A.5 A.6 B.1 B.2 B.3 TOTAL. Maximum possible points: Name: Student ID: Instructor: Borja Sotomayor Do not write in this area A.1 A.2 A.3 A.4 A.5 A.6 B.1 B.2 B.3 TOTAL Maximum possible points: 75 + 10 This homework has two parts: Part A (Polynomial ADT) and

More information

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

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional

More information

CIS 194: Homework 4. Due Wednesday, February 18, What is a Number?

CIS 194: Homework 4. Due Wednesday, February 18, What is a Number? CIS 194: Homework 4 Due Wednesday, February 18, 2015 What is a Number? This may sound like a deep, philosophical question, but the Haskell type system gives us a simple way to answer it. A number is any

More information

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

Review of Important Topics in CS1600. Functions Arrays C-strings Review of Important Topics in CS1600 Functions Arrays C-strings Array Basics Arrays An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why

More information

Problems with simple variables

Problems with simple variables Problems with simple variables Hard to give up values high number of variables. Complex to sort a high number of variables by value. Impossible to use loops. Example problem: Read one hundred numbers,

More information

Principles of Programming. Chapter 6: Arrays

Principles of Programming. Chapter 6: Arrays Chapter 6: Arrays In this chapter, you will learn about Introduction to Array Array declaration Array initialization Assigning values to array elements Reading values from array elements Simple Searching

More information

13.4 Case Study: vector<t>-based Matrices

13.4 Case Study: vector<t>-based Matrices 13.4 Case Study: vector-based Matrices 1 13.4 Case Study: vector-based Matrices A two-dimensional numeric array having m rows and n columns is called an m n matrix. There are many important applications

More information

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Michele Van Dyne Museum 204B  CSCI 136: Fundamentals of Computer Science II, Spring Michele Van Dyne Museum 204B mvandyne@mtech.edu http://katie.mtech.edu/classes/csci136 CSCI 136: Fundamentals of Computer Science II, Spring 2016 1 Review of Java Basics Data Types Arrays NEW: multidimensional

More information

Example: Computing prime numbers

Example: Computing prime numbers Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will

More information

Arrays, Pointers and Memory Management

Arrays, Pointers and Memory Management Arrays, Pointers and Memory Management EECS 2031 Summer 2014 Przemyslaw Pawluk May 20, 2014 Answer to the question from last week strct->field Returns the value of field in the structure pointed to by

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

CGS 3460 Summer 07 Midterm Exam

CGS 3460 Summer 07 Midterm Exam Short Answer 3 Points Each 1. What would the unix command gcc somefile.c -o someotherfile.exe do? 2. Name two basic data types in C. 3. A pointer data type holds what piece of information? 4. This key

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Spare Matrix Formats, and The Standard Template Library

Spare Matrix Formats, and The Standard Template Library Annotated slides CS319: Scientific Computing (with C++) Spare Matrix Formats, and The Standard Template Library Week 10: 9am and 4pm, 20 March 2019 1 Sparse Matrices 2 3 Compressed Column Storage 4 (Not)

More information

Chapter 6: Using Arrays

Chapter 6: Using Arrays Chapter 6: Using Arrays Declaring an Array and Assigning Values to Array Array Elements A list of data items that all have the same data type and the same name Each item is distinguished from the others

More information

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

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays 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

More information

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS ARRAYS A Java array is an Object that holds an ordered collection of elements. Components of an array can be primitive types or may reference objects, including other arrays. Arrays can be declared, allocated,

More information

BITG 1113: Array (Part 1) LECTURE 8

BITG 1113: Array (Part 1) LECTURE 8 BITG 1113: Array (Part 1) LECTURE 8 1 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D)

More information

More non-primitive types Lesson 06

More non-primitive types Lesson 06 CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2.

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

More information

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17 Grade Distribution Exam 1 Exam 2 Score # of Students Score # of Students 16 4 14 6 12 4 10 2 8 1 Total: 17 Exams 1 & 2 14 2 12 4 10 5 8 5 4 1 Total: 17 Score # of Students 28 2 26 5 24 1 22 4 20 3 18 2

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

More information

Variable initialization and assignment

Variable initialization and assignment Variable initialization and assignment int variable_name; float variable_name; double variable_name; String variable_name; boolean variable_name; Initialize integer variable Initialize floating point variable

More information

Ashish Gupta, Data JUET, Guna

Ashish Gupta, Data JUET, Guna Categories of data structures Data structures are categories in two classes 1. Linear data structure: - organized into sequential fashion - elements are attached one after another - easy to implement because

More information

Write a C program using arrays and structure

Write a C program using arrays and structure 03 Arrays and Structutes 3.1 Arrays Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements. (10M) 3.2 Declaration and initialization of string

More information

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Looping and Counting. Lecture 3 Hartmut Kaiser  hkaiser/fall_2012/csc1254.html Looping and Counting Lecture 3 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html Abstract First we ll discuss types and type safety. Then we will modify the program

More information

In the previous lecture, we learned about how to find the complexity of algorithms and search algorithms on array.

In the previous lecture, we learned about how to find the complexity of algorithms and search algorithms on array. Lecture 2 What we will learn 1. Definition of Arrays 2. Representation of Arrays in memory 3. Row-major Order and Column-major Order In the previous lecture, we learned about how to find the complexity

More information

PROGRAMMING II ABSTRACT DATA TYPES Assessed Coursework: DUE IN at SAO by Tuesday, 16 th March

PROGRAMMING II ABSTRACT DATA TYPES Assessed Coursework: DUE IN at SAO by Tuesday, 16 th March PROGRAMMING II ABSTRACT DATA TYPES Assessed Coursework: DUE IN at SAO by Tuesday, 16 th March 1. A classic use of linked lists is for representing and manipulating polynomials. A polynomial is a mathematical

More information

So far. Specifications, conclusion. Abstract Data Types (ADTs) Comparison by Logical Formulas. Outline

So far. Specifications, conclusion. Abstract Data Types (ADTs) Comparison by Logical Formulas. Outline So far Specifications, conclusion. Abstract Data Types (ADTs) Based on notes by Michael Ernst, University of Washington Specifications Benefits of specifications Specification conventions Javadoc JML/Dafny

More information

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists. Announcements MODULE WEB-SITE: http://www.csc.liv.ac.uk/ michele/teaching/comp102/comp102.html FIRST ASSIGNMENT DEADLINE: Wednesday, February 1st, 14.30, LAB 7 Boxes (late submissions to be left in the

More information

Finite Math - J-term Homework. Section Inverse of a Square Matrix

Finite Math - J-term Homework. Section Inverse of a Square Matrix Section.5-77, 78, 79, 80 Finite Math - J-term 017 Lecture Notes - 1/19/017 Homework Section.6-9, 1, 1, 15, 17, 18, 1, 6, 9, 3, 37, 39, 1,, 5, 6, 55 Section 5.1-9, 11, 1, 13, 1, 17, 9, 30 Section.5 - Inverse

More information

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam Multimedia Programming 2004 Lecture 2 Erwin M. Bakker Joachim Rijsdam Recap Learning C++ by example No groups: everybody should experience developing and programming in C++! Assignments will determine

More information

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Looping and Counting. Lecture 3. Hartmut Kaiser  hkaiser/fall_2011/csc1254.html Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract First we ll discuss types and type safety. Then we will modify the program we developed last time (Framing

More information

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) Review Final exam Final exam will be 12 problems, drop any 2 Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) 2 hours exam time, so 12 min per problem (midterm 2 had

More information

Basics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011

Basics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011 Basics of Java: Expressions & Statements Nathaniel Osgood CMPT 858 February 15, 2011 Java as a Formal Language Java supports many constructs that serve different functions Class & Interface declarations

More information

Computer Programming

Computer Programming Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: Recap of Arrays and Simultaneous Equations (S31 S35) Dr. Deepak B. Phatak & Dr.

More information

Submit your answers to these questions to the Curator under Quizzes as HW08 by the posted due date and time. No late submissions will be accepted.

Submit your answers to these questions to the Curator under Quizzes as HW08 by the posted due date and time. No late submissions will be accepted. Instructions: For all questions, assume that any necessary header files have been included. Submit your answers to these questions to the Curator under Quizzes as HW08 by the posted due date and time.

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

DATA STRUCTURES CHAPTER 1

DATA STRUCTURES CHAPTER 1 DATA STRUCTURES CHAPTER 1 FOUNDATIONAL OF DATA STRUCTURES This unit introduces some basic concepts that the student needs to be familiar with before attempting to develop any software. It describes data

More information

Computer Science II CSci 1200 Sections 1-4,6 Week 6, Friday Class October 5, 2001 Linked Lists, Part 2

Computer Science II CSci 1200 Sections 1-4,6 Week 6, Friday Class October 5, 2001 Linked Lists, Part 2 Computer Science II CSci 1200 Sections 1-4,6 Week 6, Friday Class October 5, 2001 Linked Lists, Part 2 Announcements Tests will be returned next Friday. We will discuss test content, test preparations,

More information

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

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type. CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer

More information

Chapter 4. LISTS. 1. Pointers

Chapter 4. LISTS. 1. Pointers Chap 4: LIST (Page 1) Chapter 4. LISTS TABLE OF CONTENTS 1. POINTERS 2. SINGLY LINKED LISTS 3. DYNAMICALLY LINKED STACKS AND QUEUES 4. POLYNOMIALS 5. ADDITIONAL LIST OPERATIONS 6. EQUIVALENCE RELATIONS

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size APS105 Malloc and 2D Arrays Textbook Chapters 6.4, 10.2 Datatype Size Datatypes have varying size: char: 1B int: 4B double: 8B int sizeof(): a builtin function that returns size of a type int x =

More information

Data Structure. Chapter 4 List (Part II) Department of Communication Engineering National Central University Jhongli, Taiwan.

Data Structure. Chapter 4 List (Part II) Department of Communication Engineering National Central University Jhongli, Taiwan. Data Structure Chapter 4 List (Part II) Angela Chih-Wei Tang Department of Communication Engineering National Central University Jhongli, Taiwan 2009 Spring Outline Polynomials Sparse matrices Doubly linked

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Chapter-8 DATA TYPES. Introduction. Variable:

Chapter-8 DATA TYPES. Introduction. Variable: Chapter-8 DATA TYPES Introduction To understand any programming languages we need to first understand the elementary concepts which form the building block of that program. The basic building blocks include

More information

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size] (November 10, 2009 2.1 ) Arrays An array is a collection of several elements of the same type. An array variable is declared as type array name[size] I The elements are numbered as 0, 1, 2... size-1 I

More information

Lecture 13: Two- Dimensional Arrays

Lecture 13: Two- Dimensional Arrays Lecture 13: Two- Dimensional Arrays Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Nested Loops Nested loops nested loop:

More information

Goals of this Lecture

Goals of this Lecture C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing

More information

The type of all data used in a C++ program must be specified

The type of all data used in a C++ program must be specified The type of all data used in a C++ program must be specified A data type is a description of the data being represented That is, a set of possible values and a set of operations on those values There are

More information

Introduction to MATLAB for Engineers, Third Edition

Introduction to MATLAB for Engineers, Third Edition PowerPoint to accompany Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2010. The McGraw-Hill Companies, Inc. This work is

More information

CS201 Spring2009 Solved Sunday, 09 May 2010 14:57 MIDTERM EXAMINATION Spring 2009 CS201- Introduction to Programming Question No: 1 ( Marks: 1 ) - Please choose one The function of cin is To display message

More information

True or False (15 Points)

True or False (15 Points) Name Number True or False (15 Points) 1. (15 pts) Circle T for true and F for false: T F a) Value Returning Functions cannot use reference parameters. T F b) Arguments corresponding to value parameters

More information

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING APS 105 Computer Fundamentals Midterm Examination October 20, 2011 6:15 p.m. 8:00 p.m. (105 minutes) Examiners: J. Anderson, T. Fairgrieve,

More information