Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Similar documents
Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

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

Chapter 2 Data Design and Implementation

Abstract Data Types. Different Views of Data:

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

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

Pointers, Dynamic Data, and Reference Types

CSC 211 Intermediate Programming. Arrays & Pointers

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Arrays. Week 4. Assylbek Jumagaliyev

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

COEN244: Class & function templates

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Fast Introduction to Object Oriented Programming and C++

Chapter 1: Object-Oriented Programming Using C++

CS242 COMPUTER PROGRAMMING

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

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CS201- Introduction to Programming Current Quizzes

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

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

Extending Classes (contd.) (Chapter 15) Questions:

Object-Oriented Programming (OOP) Fundamental Principles of OOP

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

CMSC 202 Midterm Exam 1 Fall 2015

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

Crash Course into. Prof. Dr. Renato Pajarola

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ Programming Fundamentals

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

CSCS 261 Programming Concepts Exam 2 Fall EXAM 2 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

BTE2313. Chapter 2: Introduction to C++ Programming

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

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

Object Oriented Programming CS250

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Review Questions for Final Exam

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

Exam 3 Chapters 7 & 9

CS201 - Introduction to Programming Glossary By

Module 6: Array in C

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Polymorphism Part 1 1

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Inheritance, and Polymorphism.

BITG 1113: Array (Part 1) LECTURE 8

6.096 Introduction to C++ January (IAP) 2009

Chapter 6 Introduction to Defining Classes

CS2255 HOMEWORK #1 Fall 2012

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

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

UNIT- 3 Introduction to C++

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Lab # 02. Basic Elements of C++ _ Part1

Short Notes of CS201

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Cpt S 122 Data Structures. Introduction to C++ Part II

Homework #3 CS2255 Fall 2012

Homework Assignment #2 (revised)

Classes and Objects. Class scope: - private members are only accessible by the class methods.

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CSI33 Data Structures

CSCS 261 Programming Concepts Exam 2 Fall EXAM 2 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

Functions. Introduction :

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

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

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

Pointers, Arrays and C-Strings

CS201 Latest Solved MCQs

Java Object Oriented Design. CSC207 Fall 2014

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

CS105 C++ Lecture 7. More on Classes, Inheritance

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

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.

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

True or False (15 Points)

CS260 Intro to Java & Android 03.Java Language Basics

Object Oriented Programming. Solved MCQs - Part 2

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

Lecture 04 FUNCTIONS AND ARRAYS

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

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

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

CS 247: Software Engineering Principles. ADT Design

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Instantiation of Template class

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Programming, numerics and optimization

Absolute C++ Walter Savitch

1. Which of the following best describes the situation after Line 1 has been executed?

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Transcription:

Review Fall 2017 CISC2200 Yanjun Li 1 Outline Array Pointer Object-Oriented Programming Fall 2017 CISC2200 Yanjun Li 2 1

Computer Fall 2017 CISC2200 Yanjun Li 3 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory locations. Fall 2017 CISC2200 Yanjun Li 4 2

Elements of An Array To refer to a particular location or element in the array, we specify the name of the array and the index of the element. The index must be integer or integer expression, its value must be larger than or equal to 0. First element has index zero. The element could be used as a variable. Example C[ 0 ] += 2; C[ a + b ] = 3; Fall 2017 CISC2200 Yanjun Li 5 Example An array c has 12 elements ( c[0], c[1], c[11] ); the value of c[0] is 45. Fall 2017 CISC2200 Yanjun Li 6 3

Declare An Array Declaration of an array: type arrayname[ arraysize ]; Example int c[ 12 ]; Array s size must be an integer constant greater than zero. Arrays can be declared to contain values of data types like int, float, double, char, etc. Fall 2017 CISC2200 Yanjun Li 7 Initialize An Array (1) With an initializer list Initializer list Items enclosed in braces ({}) and separated by commas. Examples int n[ 5 ] = { 10, 20, 30, 40, 50 }; int m[ 5 ] = { 10, 20, 30 }; The remaining elements are initialized to zero. int p[ ] = { 10, 20, 30, 40, 50 }; Because array size is omitted in the declaration, the compiler determines the size of the array based on the size of the initializer list. Fall 2017 CISC2200 Yanjun Li 8 4

Initialize An Array (2) Using a loop to initialize the array s elements Declare array, specify number of elements Use repetition statement to loop for each element Example: int n[10]; for ( int i = 0; i < 10; i++) { n[ i ] = 0; } Fall 2017 CISC2200 Yanjun Li 9 Using An Array Usually use for loop to access each element of an array. C++ has no array bounds checking Referring to an element outside the array bounds is an execution-time logic error. It is not a syntax error. You need to provide the correct array size. Fall 2017 CISC2200 Yanjun Li 10 5

Using An Array Example 1 Summing the elements of an array Example: const int arraysize = 6; int a [ arraysize ] = { 87, 69, 45, 45, 43, 21 }; int total = 0; for ( int i = 0; i < arraysize; i++) { total += a[i]; } cout << Total of array elements is <<total<<endl; Fall 2017 CISC2200 Yanjun Li 11 C++ Tips for Function Call Pass-by-value sends a copy of the contents of the actual parameter CALLING BLOCK FUNCTION CALLED SO, the actual parameter cannot be changed by the function Fall 12 2017 CISC2200 Yanjun Li 12 6

C++ Tips for Function Call Pass-by-reference sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED SO, the actual parameter can be changed by the function Fall 2017 13 CISC2200 Yanjun Li 13 Passing Arrays as Parameters In C++, arrays are always passed by reference, and & is not used with the formal parameter type. Whenever an array is passed as a parameter, its base address is sent to the called function. Example: // prototype float SumValues ( float values [ ], int numofvalues ); Fall 2017 CISC2200 Yanjun Li 14 7

const array parameter Because arrays are always passed as reference parameters, you can protect the actual parameter from unintentional changes by using const in formal parameter list and function prototype. FOR EXAMPLE... // prototype float SumValues(const float values[ ], int numofvalues ); Fall 2017 CISC2200 Yanjun Li 15 // Pre: values[0] through values[numofvalues-1] // have been assigned // Returns the sum of values[0] through // values[numofvalues-1] float SumValues (const float values[ ], int numofvalues ) { float sum = 0; for ( int index = 0; index < numofvalues; index++ ) { sum += values [ index ] ; } } return sum; Fall 2017 CISC2200 Yanjun Li 16 8

Multidimensional Array Multidimensional arrays with two dimensions Called two dimensional or 2-D arrays Represent tables of values with rows and columns Elements referenced with two subscripts ([x][y]) In general, an array with m rows and n columns is called an m-by-n array Multidimensional arrays can have more than two dimensions Fall 2017 CISC2200 Yanjun Li 17 Declaring & Initializing Two-Dimensional Arrays Declaring two-dimensional array b int b[ 3 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ] 3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ] 0 and 0 initialize b[ 2 ][ 0 ] and b[ 2 ][ 1 ] (implicitly). Column 0 Column 1 Row 0 1 2 Row 1 3 4 Row 2 0 0 Fall 2017 CISC2200 Yanjun Li 18 9

Two-Dimensional Array Fall 2017 CISC2200 Yanjun Li 19 Passing Multidimensional Arrays to Functions Multidimensional array parameters Size of first dimension is not required As with a one-dimensional array Size of subsequent dimensions are required Compiler must know how many elements to skip to move to the second element in the first dimension Example void printarray( const int a[][ 3 ] ); Function will skip row 0 s 3 elements to access row 1 s elements (a[ 1 ][ x ]) Fall 2017 CISC2200 Yanjun Li 20 10

Implementation Level View statehighs[ 0 ] [ 0 ] statehighs[ 0 ] [ 1 ] statehighs[ 0 ] [ 2 ] statehighs[ 0 ] [ 3 ] statehighs[ 0 ] [ 4 ] statehighs[ 0 ] [ 5 ] statehighs[ 0 ] [ 6 ] statehighs[ 0 ] [ 7 ] statehighs[ 0 ] [ 8 ] statehighs[ 0 ] [ 9 ] statehighs[ 0 ] [10 ] statehighs[ 0 ] [11 ] statehighs[ 1 ] [ 0 ] statehighs[ 1 ] [ 1 ] statehighs[ 1 ] [ 2 ] statehighs[ 1 ] [ 3 ]... Base Address 8000 To locate an element such as statehighs [ 2 ] [ 7] the compiler needs to know that there are 12 columns in this two-dimensional array. At what address will statehighs [ 2 ] [ 7 ] be found? Assume 2 bytes for type int. Fall 2017 CISC2200 Yanjun Li 21 Multidimensional-Array Manipulations Commonly performed with for statements Example Modify all elements in a row for ( int col = 0; col < 4; col++ ) a[ 2 ][ col ] = 0; Example Total all elements total = 0; for ( int row = 0; row < 3; row++ ) for ( int col = 0; col < 4; col++ ) total += a[ row ][ col ]; Fall 2017 CISC2200 Yanjun Li 22 11

Pointer Types Pointer variable A variable whose value is the address of a location in memory int* intpointer Fall 2017 CISC2200 Yanjun Li 23 int alpha; int* intpointer; intpointer = α Pointer Types If alpha is at address 33, memory looks like this Fall 2017 CISC2200 Yanjun Li 24 12

Pointer Types int x; x = 12; 2000 x 12 int* ptr; ptr = &x; 3000 ptr 2000 NOTE: Because ptr holds the address of x, we say that ptr points to x Fall 2017 CISC2200 Yanjun Li 25 Pointer Types Dereference operator (*) An operator that, when applied to a pointer variable, denotes the variable to which the pointer points Fall 2017 CISC2200 Yanjun Li 26 13

Pointer Types int x; x = 12; int* ptr; ptr = &x; std::cout << *ptr; 3000 ptr 2000 2000 x 12 *ptr is the value in the place to which ptr points Fall 2017 CISC2200 Yanjun Li 27 Pointer Types int x; x = 12; int* ptr; ptr = &x; *ptr = 5; // changes the value // at adddress ptr to 5 3000 2000 ptr 2000 12 5 x Fall 2017 CISC2200 Yanjun Li 28 14

char ch; ch = A ; char* q; q = &ch; *q = Z ; char* p; p = q; Pointer Types 4000 A Z ch 5000 6000 4000 4000 q p // the right side has value 4000 // now p and q both point to ch Fall 2017 CISC2200 Yanjun Li 29 Pointer Types Dynamic allocation (new operator) Allocation of memory space for a variable at run time (as opposed to static allocation at compile time) Fall 2017 CISC2200 Yanjun Li 30 15

Pointer Types int * intpointer; intpointer = new int; Fall 2017 CISC2200 Yanjun Li 31 NULL Pointer Pointer Types A pointer that points to nothing; available in <cstdlib> NULL is defined to be 0; But NULL is not memory address 0; int * intptr = NULL; Float * money = NULL; intptr money Fall 2017 CISC2200 Yanjun Li 32 16

Pointer Types Memory Leak The loss of available memory space that occurs when memory is allocated dynamically but never deallocated float * mymoney = new float; float * money = new float; mymoney = money; //wrong Garbage Memory locations that can no longer be accessed To avoid memory leaks, use delete. delete mymoney; //correct mymoney = money; Fall 2017 CISC2200 Yanjun Li 33 Pointer and Array Dynamically create array with pointers int * foo; foo = new int[5]; delete [] foo; The system dynamically allocate space for 5 elements of type int and returns the memory address of the first element of the array, which is assigned to foo (the pointer). Fall 2017 CISC2200 Yanjun Li 34 17

Object-Oriented Programming objects, sending a message, methods, instance variables. Object An instance of a class Method A public member function of a class Instance variable (Data Member) A private data member of a class Fall 2017 CISC2200 Yanjun Li 35 C++ class data type A class is an unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate them. Fall 2017 CISC2200 Yanjun Li 36 18

class DateType Specification // SPECIFICATION FILE ( datetype.h ) class DateType { public : // declares a class data type // 4 public member functions DateType (int newmonth,int newday,int newyear);//constructor int getyear( ) const ; // returns year int getmonth( ) const ; // returns month int getday( ) const ; // returns day private : // 3 private data members int year ; int month ; int day ; } ; Fall 2017 CISC2200 Yanjun Li 37 37 2 separate files for class type // SPECIFICATION FILE ( datetype.h ) // Specifies the data and function members. class DateType { public:... private:... } ; // IMPLEMENTATION FILE ( datetype.cpp ) // Implements the DateType member functions.... Fall 2017 CISC2200 Yanjun Li 38 19

Code Using DateType #include datetype.h //includes specification of the class #include <iostream> using namespace std; int main ( ) { // declares 2 objects of DateType DateType startdate ( 6, 30, 1998 ) ; DateType enddate ( 10, 31, 2002 ) ; bool retired = false ; } cout << startdate.getmonth( )<< / << startdate.getday( ) << / << startdate.getyear( ) << endl; while (! retired ) { finishsometask( ) ;... } return 0; Fall 2017 CISC2200 Yanjun Li 39 39 Implementation of member functions // IMPLEMENTATION FILE (datetype.cpp) #include datetype.h // also must appear in client code DateType :: DateType ( int newmonth, int newday, int newyear ) // Post: year is set to newyear. // month is set to newmonth. // day is set to newday. { year = newyear ; month = newmonth ; day = newday ; } Fall 2017 CISC2200 Yanjun Li 40 40 20

int DateType :: getmonth ( ) const // Accessor function for data member month { return month ; } int DateType :: getyear ( ) const // Accessor function for data member year { return year ; } int DateType :: getday ( ) const // Accessor function for data member day { return day ; } Fall 2017 CISC2200 Yanjun Li 41 41 Object-Oriented Programming Three ingredients in any object-oriented language encapsulation inheritance polymorphism Just as a capsule protects its contents, the class construct protects its data members, but what are inheritance and polymorphism? Fall 2017 CISC2200 Yanjun Li 42 21

Object-Oriented Programming Inheritance A mechanism used with a hierarchy of classes in which each descendant class inherits the properties (data and operations) of its ancestor class Base class The class being inherited from Derived class the class that inherits Fall 2017 CISC2200 Yanjun Li 43 Object-Oriented Programming Inheritance is an "is-a" relationship: a wheeled vehicle is a vehicle; a bicycle is a wheeled vehicle a four-door car is a car Fall 2017 CISC2200 Yanjun Li 44 22

Object-Oriented Programming Overriding Function with virtual keyword in base class. Derived classes override function as appropriate. An overridden function in a derived class has the same signature and return type (i.e. prototype) as the function it overrides in its base class. Polymorphism The ability to determine which of several operations with the same name is appropriate; a combination of static and dynamic binding Fall 2017 CISC2200 Yanjun Li 45 Object-Oriented Programming Person Employee Manager Each class has a method Print Person.Print just prints the name Employee.Print prints the name and job title Manager.Print prints name, job title, and department Print is overriden. Static binding is when the compiler can tell which Print to use; dynamic binding is when the determination cannot be made until run time Fall 2017 CISC2200 Yanjun Li 46 23

Object-Oriented Programming Inheritance and polymorphism work together How? They combine to allow the programmer to build useful hierarchies of classes that can be put into a library to be reused in different applications Fall 2017 CISC2200 Yanjun Li 47 Reference Reproduced from C++ Plus Data Structures, 4 th edition by Nell Dale. Reproduced by permission of Jones and Bartlett Publishers International. Fall 2017 CISC2200 Yanjun Li 48 24