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

Similar documents
Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 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,

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

COEN244: Class & function templates

Object-Oriented Programming (OOP) Fundamental Principles of OOP

CMSC 202 Midterm Exam 1 Fall 2015

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

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

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)

BTE2313. Chapter 2: Introduction to C++ Programming

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

Review Questions for Final Exam

Exam 3 Chapters 7 & 9

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

CS201 - Introduction to Programming Glossary By

Object Oriented Programming CS250

Polymorphism Part 1 1

Inheritance, and Polymorphism.

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.

Module 6: Array in C

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

BITG 1113: Array (Part 1) LECTURE 8

Java Object Oriented Design. CSC207 Fall 2014

CS2255 HOMEWORK #1 Fall 2012

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

6.096 Introduction to C++ January (IAP) 2009

UNIT- 3 Introduction to C++

Chapter 6 Introduction to Defining Classes

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

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

Short Notes of CS201

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

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

Homework #3 CS2255 Fall 2012

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

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

Homework Assignment #2 (revised)

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

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

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CSI33 Data Structures

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

Lecture 04 FUNCTIONS AND ARRAYS

Functions. Introduction :

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

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

Pointers, Arrays and C-Strings

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

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

CS201 Latest Solved MCQs

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

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.

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

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)

Simplest version of DayOfYear

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

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

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

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

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

Object Oriented Programming. Solved MCQs - Part 2

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):

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

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

Programming, numerics and optimization

Absolute C++ Walter Savitch

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

C++ Programming: Polymorphism

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

Arrays. int Data [8] [0] [1] [2] [3] [4] [5] [6] [7]

Chapter 2: Basic Elements of C++

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

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Transcription:

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

Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory locations. Fall 2013 CISC2200 Yanjun Li 3 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 2013 CISC2200 Yanjun Li 4 2

Example An array c has 12 elements ( c[0], c[1], c[11] ); the value of c[0] is 45. Fall 2013 CISC2200 Yanjun Li 5 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 2013 CISC2200 Yanjun Li 6 3

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 2013 CISC2200 Yanjun Li 7 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 2013 CISC2200 Yanjun Li 8 4

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 2013 CISC2200 Yanjun Li 9 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 endl; Fall 2013 CISC2200 Yanjun Li 10 5

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 2013 CISC2200 Yanjun Li 11 C++ Tips 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 2013 CISC2200 Yanjun Li 12 6

C++ Tips 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 2013 13 CISC2200 Yanjun Li 13 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 2013 CISC2200 Yanjun Li 14 7

// 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 2013 CISC2200 Yanjun Li 15 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 2013 CISC2200 Yanjun Li 16 8

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). Row 0 Row 1 Row 2 Column 0 1 3 0 Column 1 2 4 0 Fall 2013 CISC2200 Yanjun Li 17 Two-Dimensional Array Fall 2013 CISC2200 Yanjun Li 18 9

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 2013 CISC2200 Yanjun Li 19 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 2013 CISC2200 Yanjun Li 20 10

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 2013 CISC2200 Yanjun Li 21 Pointer Types Pointer variable A variable whose value is the address of a location in memory int* intpointer Fall 2013 CISC2200 Yanjun Li 22 11

int alpha; int* intpointer; intpointer = α Pointer Types If alpha is at address 33, memory looks like this Fall 2013 CISC2200 Yanjun Li 23 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 2013 CISC2200 Yanjun Li 24 12

Pointer Types Dereference operator (*) An operator that, when applied to a pointer variable, denotes the variable to which the pointer points Dynamic allocation (new operator) Allocation of memory space for a variable at run time (as opposed to static allocation at compile time) Fall 2013 CISC2200 Yanjun Li 25 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 2013 CISC2200 Yanjun Li 26 13

Pointer Types int x; x = 12; int* ptr; ptr = &x; *ptr = 5; 3000 2000 ptr 2000 12 5 x // changes the value // at adddress ptr to 5 Fall 2013 CISC2200 Yanjun Li 27 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 2013 CISC2200 Yanjun Li 28 14

Pointer Types int * intpointer; intpointer = new int; Fall 2013 CISC2200 Yanjun Li 29 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 2013 CISC2200 Yanjun Li 30 15

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 delete. To avoid memory leaks, use delete delete mymoney; //correct mymoney = money; Fall 2013 CISC2200 Yanjun Li 31 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 2013 CISC2200 Yanjun Li 32 16

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 2013 CISC2200 Yanjun Li 33 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 2013 CISC2200 Yanjun Li 34 34 17

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 2013 CISC2200 Yanjun Li 35 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 2013 CISC2200 Yanjun Li 36 36 18

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 2013 CISC2200 Yanjun Li 37 37 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 2013 CISC2200 Yanjun Li 38 38 19

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 2013 CISC2200 Yanjun Li 39 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 2013 CISC2200 Yanjun Li 40 20

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 2013 CISC2200 Yanjun Li 41 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 What is the root of the word polymorphism? Fall 2013 CISC2200 Yanjun Li 42 21

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 2013 CISC2200 Yanjun Li 43 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 2013 CISC2200 Yanjun Li 44 22

Reference Reproduced from C++ Plus Data Structures, 4 th edition by Nell Dale. Reproduced by permission of Jones and Bartlett Publishers International. Fall 2013 CISC2200 Yanjun Li 45 23