Object-Oriented Programming Using C++

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Advertisements

Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
CS 141 Computer Programming 1 1 Pointers. Pointer Variable Declarations and Initialization Pointer variables –Contain memory addresses as values –Normally,
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
C++ Data Type String A string is a sequence of characters enclosed in double quotes. Examples of strings: “Hello” “CIS 260” “Students” The empty string.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Lesson 6 - Pointers Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using the const.
 2000 Deitel & Associates, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
 2006 Pearson Education, Inc. All rights reserved Pointers.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
[S. Uludag] CIS / CSC 175 Problem Solving and Programming I Winter 2010 Suleyman Uludag Department of Computer Science, Engineering and Physics (CSEP)
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
C++ Programming Lecture 17 Pointers – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
1 Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization 5.3Pointer Operators 5.4Calling Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 namespaces Program has identifiers in different scopes –Sometimes scopes overlap, lead to problems Namespace.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
1 Understanding Arrays and Pointers COSC1567 C++ Programming Lecture 2.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Pointers What is the data type of pointer variables?
Chapter 7 - Pointers Outline 7.1 Introduction
Computer Programming BCT 1113
Chapter 7 - Pointers Outline 7.1 Introduction
Pointers and Pointer-Based Strings
CSC113: Computer Programming (Theory = 03, Lab = 01)
8 Pointers.
C Arrays.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
CS 2308 Exam I Review.
7 Arrays.
Arrays Kingdom of Saudi Arabia
Pointers and Pointer-Based Strings
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Pointers Kingdom of Saudi Arabia
5.1 Introduction Pointers Powerful, but difficult to master
7 Arrays.
C++ Pointers and Strings
EENG212 ALGORITHMS & DATA STRUCTURES
C++ Programming Lecture 17 Pointers – Part I
Pointers and Pointer-Based Strings
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Arrays Arrays A few types Structures of related data items
Data Structures and Algorithms Introduction to Pointers
CS250 Introduction to Computer Science II
Lecture 2 Arrays & Pointers May 17, 2004
C++ Programming Lecture 18 Pointers – Part II
C++ Programming Lecture 20 Strings
Chapter 3 Arrays Dr. A. PHILIP AROKIADOSS Assistant Professor
Lecture 2 Arrays & Pointers September 7, 2004
CISC181 Introduction to Computer Science Dr
C++ Pointers and Strings
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Object-Oriented Programming Using C++ Understanding Arrays, Strings, and Pointers

Learn about memory addresses Learn about arrays Objectives Learn about memory addresses Learn about arrays Store values in an array Access and use array values Avoid common errors with arrays Learn techniques to access part of an array

Objectives (continued) Use parallel arrays Learn how to use strings Discover special string-handling problems Learn about pointers Use a pointer in place of an array name

Understanding Memory Addresses Each location where a piece of data can be stored is identified by a memory address When you declare a variable with a statement such as int myAge; The computer chooses an available memory location Associates the name myAge with the memory address of that location

Understanding Memory Addresses (continued) Address operator Address appears as a hexadecimal number

Understanding Arrays Array: list of items that all have the same type Subscript: number that indicates the position of the particular array element being used Element: single object in an array double moneyCollected[5];

Understanding Arrays (continued) int someNumbers[7]; If you access someNumbers[7], you may get a warning or a garbage value cout<<someNumbers produces the same output as cout<<&someNumbers[0]

Storing Values in an Array int rent[4]; rent[0] = 250; rent[1] = 375; rent[2] = 460; rent[3] = 600; int rent[4] = {250, 375, 460, 600}; int rent[] = {250, 375, 460, 600}; int rent[4] = {250, 375}; int rent[3] = {250, 375, 460, 600}; int rent[4] = {0}; rent[2] and rent[3] are set to 0 Syntax error Sets all array elements to 0

Accessing and Using Array Values

Accessing and Using Array Values (continued) You can also use a variable as a subscript

Accessing and Using Array Values (continued)

Accessing and Using Array Values (continued)

Avoiding Common Array Errors When working with arrays, common errors include: Forgetting that arrays are zero based Accessing locations beyond the array

Forgetting that Arrays are Zero-Based

Accessing Locations Beyond the Array Element is out of bounds

Using Part of an Array Sentinel

Using Part of an Array (continued) Tip: You cannot use a variable to declare an array’s size; you must use a constant

Using Parallel Arrays Parallel arrays are corresponding arrays in which values in the same relative locations are logically related

Using Parallel Arrays (continued)

Using Parallel Arrays (continued)

Using Parallel Arrays (continued) Flag could also be of type bool

Creating Arrays of Structure Objects

Using Strings String: value expressed within double quotes You can type two characters within single quotes when they represent a single character: ‘\n’ “Hello” is a string constant To store a value such as “Hello” -> must create a string variable in one of two ways: Create a string as an array of characters Create a string using the string class defined in the C++ standard library

Strings Created as Arrays of Characters char firstName[] = “Mary”; char firstName[] = {“Mary”}; char firstName[5] = “Mary”; char firstName[5] = {“Mary”}; char firstName[5] = {'M', 'a', 'r', 'y', '\0'}; cout<<firstName; // displays Mary cout<<&firstName[1]; // displays ary Null character. You could also use the constant NULL, defined in iostream

Special String-Handling Problems When Using Character Arrays Some problems occur when strings are declared as character arrays and you: Try to input a string value that includes whitespace Try to assign one string to another using the assignment operator Try to compare strings using the comparison operator Exceed the bounds of an array

Trying to Input a String Value Including Whitespace

Trying to Input a String Value Including Whitespace (continued)

Trying to Assign One String to Another Using the Assignment Operator char clubPresident[10] = {“Eric”}; clubVicePresident[10] = {“Danielle”}; Alternative 1 (does not work as expected): clubPresident = clubVicePresident; Alternative 2 (tedious): clubPresident[0] = clubVicePresident[0]; clubPresident[1] = clubVicePresident[1]; clubPresident[2] = clubVicePresident[2]; Alternative 3 (must include string.h): strcpy(clubPresident, clubVicePresident);

Trying to Compare Strings Using the Comparison Operator Alternative 1 (does not work as expected): if(clubPresident == clubVicePresident) cout<<”They are the same”<<endl; Alternative 2 (tedious): if(clubPresident[0] == clubVicePresident[0] && clubPresident[1] == clubVicePresident[1]. . . Alternative 3 (must include string.h): strcmp(firstName, secName); A return value of 0 indicates they are equal

Exceeding an Array’s Bounds

Pitfall: Exceeding an Array’s Bounds (continued)

An Introduction to the string Class

An Introduction to the string Class (continued)

Pointers: variables that can hold memory addresses Using Pointers Pointers: variables that can hold memory addresses A pointer’s type indicates the type of variable that has an address the pointer can hold For example, int *aPointer; int myValue; aPointer = &myValue; cout<<myValue; //outputs contents of myValue cout<<*aPointer; //outputs contents of myValue cout<<&myValue; //outputs address of myValue cout<<aPointer; //outputs address of myValue

Pointer Variable Declarations and Initialization Can declare pointers to any data type Pointer initialization Initialized to 0, NULL, or address 0 or NULL points to nothing

Pointer Operators & (address operator) Returns memory address of its operand Example int y = 5; int *yPtr; yPtr = &y; // yPtr gets address of y - yPtr “points to” y

* (indirection/dereferencing operator) Pointer Operators * (indirection/dereferencing operator) Returns synonym for object its pointer operand points to *yPtr returns y (because yPtr points to y). dereferenced pointer is 1 value *yptr = 9; // assigns 9 to y * and & are inverses of each other

Using const with Pointers const qualifier Value of variable should not be modified const used when function does not need to change a variable Principle of least privilege Award function enough access to accomplish task, but no more Four ways to pass pointer to function Nonconstant pointer to nonconstant data Highest amount of access Nonconstant pointer to constant data Constant pointer to nonconstant data Constant pointer to constant data Least amount of access

Using const with Pointers const pointers Always point to same memory location Default for array name Must be initialized when declared

Example int main() { int x, y; // ptr is a constant pointer to an integer that can // be modified through ptr, but ptr always points to the // same memory location. int * const ptr = &x; //but if int const *ptr=&x then red line is error //and magenta line is not error *ptr = 7; // allowed: *ptr is not const ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main

Example int main() { int x = 5, y; // ptr is a constant pointer to a constant integer. // ptr always points to the same location; the integer // at that location cannot be modified. const int *const ptr = &x; cout << *ptr << endl; *ptr = 7; // error: *ptr is const; cannot assign new value ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main

Using a Pointer Instead of an Array Name

Using a Pointer Instead of an Array Name (continued)

You Do It: Using an Array

Understanding Memory Addresses cout << "The addresses are " << &firstNum <<" and " << &secondNum << endl;

Summary Each location where a piece of data can be stored is identified by a memory address A list of individual items that all have the same type is called an array A subscript indicates the position of an array element You can initialize an array when you declare it You can access an individual array value just as you would access any variable of the same type

Summary (continued) Common errors when using arrays include: Forgetting that arrays are zero-based Forgetting that the highest legitimate subscript is one less than the array size Use a for loop to access all array elements Parallel arrays contain corresponding elements You can create arrays of structure objects

Summary (continued) A C++ value expressed within double quotes is commonly called a string You can create a string variable As an array of characters With the string class from the C++ standard library Pointers are variables that hold memory addresses To indicate a pointer, begin the variable’s name with an asterisk

Exercises Binary search Only used with sorted arrays Compare middle element with key If equal, match found If key < middle Repeat search on first half of array If key > middle Repeat search on last half

Bubble Sort Using Pass-by-Reference Exercises Bubble Sort Using Pass-by-Reference Implement BubbleSort using pointers Want function swap to access array elements Individual array elements: scalars Passed by value by default Pass by reference using address operator &

Exercises Tokenizing