SlideShare a Scribd company logo
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3
Objectives In this chapter, you will learn: How to use the address operator About arrays How to store values in an array How to access and use array values The value of using a constant to refer to an array’s size 3
Objectives In this chapter, you will learn: Techniques to access some of the values in an array  How to use parallel arrays How to use strings About special string-handling problems About pointers How to use a pointer in place of an array name 3
Using the Address Operator A variable’s memory address is a fixed location; a variable’s address is a constant Although you cannot choose a variable’s actual memory address, you can examine it To do so, you use the address operator (&) The output is shown in Figure 3-2 The memory address is of not use to you at this point; you use the address operator merely as a curiosity The hexadecimal numbering system uses the values 0 through 9, and the letters a through f to represent the decimal values 0 through 15 3
Using the Address Operator 3 F3-1.cpp //console I/O
Using the Address Operator In the steps listed on pages 73 and 74 of the textbook, you will experiment with memory addresses in your computer system 3 F3-3.cpp & F3-4.cpp
Understanding Arrays A list of individual items that all have the same type is called an  array An array holds two or more variables with the same name and type in adjacent memory positions The variables with the same name are distinguished from one another by their subscripts; the  subscript  is a number that indicates the position of the particular array element being used Anytime you need many related variables, consider using an array 3
Understanding Arrays In C++, you declare an array by using the form  type arrayName [size];   where  type  is any simple type,  arrayName  is any legal identifier, and  size  (in the square bracket) represents the number of elements the array contains An  element  is a single object in an array An array name actually represents a memory address When you declare an array, you tell the compiler to use the array name to indicate the beginning address of a series of elements 3
Understanding Arrays The subscript used to access an element of an array indicates how much to add to the starting address to locate a value 3
Storing Values in an Array You most often create an array when you want to store a number of related variable elements  When you declare an array like  int array [4];,  you set aside enough memory to hold four integers, but you say nothing about the values stored in those four memory locations The values are unknown—they are whatever was stored in those memory locations before the computer reserved the locations for use by your program Programmers often say that these memory locations are filled with  garbage , or useless values 3
Storing Values in an Array Just as you can initialize a single variable when you declare it, you can provide values for an array when you declare it The statement int rent[4] = {250, 375, 460, 600}; provides four values for the array If you declare an array without a size, but provide initialization values, C++ creates an array with the exact size you need If you do not provide enough values to fill an array, C++ fills any unassigned array elements with zeros 3
Program that Uses Single  and Array Variables 3 F3-6.cpp
Accessing and Using Array  Values Once an array is filled with values, you can access and use an individual array value in the same manner you would access and use any single variable of the same type If you need to access an element in an array, you can use the array name and a constant subscript such as 0 or 1 Alternately, you can use a variable as a subscript 3
Accessing and Using Array  Values The for loop prints arrayInt[0] through arrayInt[4] because x increases from 0 and remains less than 5 When the code in Figure 3-9 executes, the user will be prompted 10 times and allowed to enter a floating point value after each prompt The 10 values will be stored in price[0] through price[9], respectively 3
Accessing and Using Array  Values 3
Using a Constant to Refer  to an Array’s Size Often, using a for loop is a convenient way to access all array elements because arrays always have a specific, known size, and for loops execute a specific, known number of times When you want to access all array elements in sequential order, you can use a subscript that you vary from 0 to 1 less than the number of elements of the array Figure 3-10 shows a program that declares an array with 12 elements 3
Using a Constant to Control  Loops 3 F3-10.cpp
Accessing Elements in an  Array When you want to access a single array element, you use a subscript that indicates the position of the value you want to access When you want to access all of the elements in an array, a for loop usually is convenient The program in Figure 3-11 declares an array for 30 integer test scores, and single variables that serve as subscripts, a total, and the average A  sentinel  or  dummy  is any value that stops a loop’s execution You enter the program from Figure 3-11 and modify the program to better understand some of its properties and discover some of its flaws, using the procedures on pages 82 and 83 of the textbook 3
A Program That Averages  Up to 30 Test Scores 3 F3-11.cpp
Using Parallel Arrays When you want to access an array element, you use the appropriate subscript If each array element’s position has a logical connection to the array value’s purpose, accessing an array value is a straightforward process Sometimes the numbers you need to access appropriate array values are not small whole numbers 3
A Program That Determines  Insurance Premiums 3 F3-12.cpp
Using Parallel Arrays If you write a program in which you ask the user for a part number so that you can display the price, you cannot use the part number as a subscript to a price array unless you create a price array with at least 456 elements Creating an array with 456 elements that need to store four prices is cumbersome and inefficient 3
Using Parallel Arrays A better solution is to create two arrays of just four elements each—one to hold the four part numbers, and one to hold the four prices that correspond to those part numbers Such corresponding arrays are called  parallel arrays 3
Program That Determines  Part Prices 3 F3-14.cpp F3-14.cpp
Using Parallel Arrays Create the program that determines the correct price number for a part, and then improve the program by following the instructions on pages 85 to 87 of the textbook 3
Creating Arrays of Class  Objects Just as you can create arrays of simple types such as int and double, you can create arrays of class objects The program in Figure 3-16 creates an array of four Automobile objects To access any individual class object field, you use the object’s individual name, including its subscript, followed by a dot and the field name 3
Creating an Array of Class Objects 3 F3-15
Output of Program from  Figure 3-16 3
Using Strings In C++, a character variable can hold a single character value, such as ‘A’ or ‘$’ Single character values are always expressed within single quotation marks In C++, if you want to express multiple character values, such as a first name or a book title, you use double quotation marks A C++ value expressed within double quotation marks is commonly called a  string 3
Using Strings You already have used strings with cout statements, as in cout<<“Hello”; Just as a value such as 14 is a numeric constant, a value such as “Hello” is referred to as a  string constant In C++ an array of characters and a string are declared in the same way You might create an array of characters if you need to store six one-letter department codes, or five one-letter grades that can be assigned on a test 3
Using Strings The  null character  is represented by the combination ‘\0’ (backslash and zero), or by using the constant NULL that is available if you use the statement #include,<iostream.h> at the top of any file you compile 3
Special String Handling  Problems String present some special handling problems When you use the cin statement with a string, cin stops adding characters to the string when it encounters white space Often, this means that cin stops when the user presses the Enter key But cin also stops when the user presses the spacebar or the Tab key 3
A Program That Reads a Name 3
Special String Handling  Problems When the user types Mark Ann in the program in Figure 3-19, the cin statement accepts Mary into the string and leaves Ann waiting in an area called the  input buffer If the program contains a subsequent cin statement, then Ann is accepted and assigned to the string named in the second cin statement 3
Special String Handling  Problems 3
Special String Handling  Problems Another string handling problem occurs when you attempt to assign one string to another To assign the name of the clubPresident to the same name as the clubVicePresident, you must assign each character value in the clubVicePresident name to the corresponding character location in the clubPresident name A related string-handling problem occurs when you try to compare two strings 3
Special String Handling  Problems If you want to determine whether clubPresident and clubVicePresident have the same name, it might seem natural to write a statement such as: if(clubPresident == clubVicePresident) cout<<“They are the same”<<endl; You could write instructions to compare two strings by each character of one string to the corresponding character in the other string, such as in the following: if(clubPresident[0]==clubVicePresident[0] && clubPresident[1]==clubVicePresident[1]. . .  3
Using the strcmp() Function 3 F3-23.cpp
Special String Handling  Problems You also can replace this tedious method with the built-in function strcmp( ) Declaring an array of strings poses a few special problems To solve them, you must learn to use a two-dimensional array 3
Using Pointers You also can declare variables that can hold memory addresses These variables are called pointer variables, or simply  pointers You declare a pointer with a type, just like other variables The major difference between using a pointer name and the address operator with a variable name is that a pointer is a variable 3
Using a Pointer Instead of  an Array Name Advanced C++ programmers use pointers for many purposes Sometimes they use a pointer as an alternative to an array name The program illustrated in Figure 3-25 shows four different ways to access the same seven values The program declares an integer array with sales figures for seven days for a small business The program also declares an integer pointer and assigns the address of the first sales figure to that pointer 3
A Program That Uses Array  and Pointer Notation 3 F3-25.cpp
Output of Program From  Figure 3-25 3
Using Pointers to Hold Strings 3 F3-27.cpp
Using a Pointer Instead of  an Array Name Because pointers access computer memory locations, using pointers can be dangerous because you might point to an alter memory locations that you had no intention of altering A  dangling reference  is when you delete the value pointed to by one of the pointers, and the other pointer is left without a value 3

More Related Content

What's hot (20)

PPTX
Friend functions
Megha Singh
 
PPT
Function overloading(c++)
Ritika Sharma
 
PPTX
Data types in c++
Venkata.Manish Reddy
 
PPTX
C# Arrays
Hock Leng PUAH
 
PPTX
Arrays in c
CHANDAN KUMAR
 
PPT
applications of computer graphics
Aaina Katyal
 
PPTX
2- Dimensional Arrays
Education Front
 
PPTX
Managing input and output operations in c
niyamathShariff
 
PPTX
Function Pointer
Dr-Dipali Meher
 
PPTX
Arrays
Trupti Agrawal
 
PPTX
Operator overloading
Burhan Ahmed
 
PPTX
Friend function
zindadili
 
PPT
C++ data types
pratikborsadiya
 
PDF
C++ chapter 1
jasvinder162
 
PPTX
Operators in java
Then Murugeshwari
 
PPTX
Operators and expressions in c language
tanmaymodi4
 
PDF
Class and Objects in Java
Spotle.ai
 
PPTX
Row major and column major in 2 d
nikhilarora2211
 
PPS
Wrapper class
kamal kotecha
 
PPTX
Constants in java
Manojkumar C
 
Friend functions
Megha Singh
 
Function overloading(c++)
Ritika Sharma
 
Data types in c++
Venkata.Manish Reddy
 
C# Arrays
Hock Leng PUAH
 
Arrays in c
CHANDAN KUMAR
 
applications of computer graphics
Aaina Katyal
 
2- Dimensional Arrays
Education Front
 
Managing input and output operations in c
niyamathShariff
 
Function Pointer
Dr-Dipali Meher
 
Operator overloading
Burhan Ahmed
 
Friend function
zindadili
 
C++ data types
pratikborsadiya
 
C++ chapter 1
jasvinder162
 
Operators in java
Then Murugeshwari
 
Operators and expressions in c language
tanmaymodi4
 
Class and Objects in Java
Spotle.ai
 
Row major and column major in 2 d
nikhilarora2211
 
Wrapper class
kamal kotecha
 
Constants in java
Manojkumar C
 

Viewers also liked (20)

PPTX
Array in c++
Mahesha Mano
 
PPTX
C++ Pointers
Chaand Sheikh
 
PDF
Pointers & References in C++
Ilio Catallo
 
DOCX
Pratik Bakane C++
pratikbakane
 
PPTX
C++ programming (Array)
طارق بالحارث
 
PPTX
Pointers in c++
Rajat Busheheri
 
PDF
C++ ARRAY WITH EXAMPLES
Farhan Ab Rahman
 
PDF
Pointer in c++ part1
Subhasis Nayak
 
PPTX
Arrays In C++
Awais Alam
 
PPT
Arrays
archikabhatia
 
PPT
Structured Data Type Arrays
Praveen M Jigajinni
 
PPTX
Grow Your Career with WordPress
Tareq Hasan
 
PDF
Arrays in C++
Ilio Catallo
 
PPT
More Pointers and Arrays
emartinez.romero
 
PPT
C++ programming
viancagerone
 
PPT
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
PDF
Php, mysq lpart5(mysql)
Subhasis Nayak
 
PDF
Array in Java
Ali shah
 
DOCX
Pratik Bakane C++
pratikbakane
 
PPTX
Classes and objects till 16 aug
shashank12march
 
Array in c++
Mahesha Mano
 
C++ Pointers
Chaand Sheikh
 
Pointers & References in C++
Ilio Catallo
 
Pratik Bakane C++
pratikbakane
 
C++ programming (Array)
طارق بالحارث
 
Pointers in c++
Rajat Busheheri
 
C++ ARRAY WITH EXAMPLES
Farhan Ab Rahman
 
Pointer in c++ part1
Subhasis Nayak
 
Arrays In C++
Awais Alam
 
Structured Data Type Arrays
Praveen M Jigajinni
 
Grow Your Career with WordPress
Tareq Hasan
 
Arrays in C++
Ilio Catallo
 
More Pointers and Arrays
emartinez.romero
 
C++ programming
viancagerone
 
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
Php, mysq lpart5(mysql)
Subhasis Nayak
 
Array in Java
Ali shah
 
Pratik Bakane C++
pratikbakane
 
Classes and objects till 16 aug
shashank12march
 
Ad

Similar to 02 c++ Array Pointer (20)

PPTX
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
teddiyfentaw
 
PPTX
Chapter-Five.pptx
berekethailu2
 
PDF
1-Intoduction ------------- Array in C++
ab6399671
 
PPT
CHAPTER-5.ppt
Tekle12
 
PPTX
CSCI 238 Chapter 08 Arrays Textbook Slides
DanWooster1
 
PPTX
Lecture 7
Mohammed Khan
 
PPTX
Lecture 9
Mohammed Khan
 
PPTX
Arrays_in_c++.pptx
MrMaster11
 
PPTX
Array,string structures. Best presentation pptx
Kalkaye
 
PPTX
Array In C++ programming object oriented programming
Ahmad177077
 
PPTX
Arrays_and_Strings_in_C_Programming.pptx
samreenghauri786
 
PDF
Arrays and library functions
Swarup Kumar Boro
 
PDF
Arrays
ViniVini48
 
PPT
C++ Arrays
أحمد محمد
 
PPT
C++ Arrays
أحمد محمد
 
PPT
C96e1 session3 c++
Mukund Trivedi
 
PPT
Lec 25 - arrays-strings
Princess Sam
 
PPTX
ARRAYS.pptx
MamataAnilgod
 
PPTX
One dimensional arrays
Satyam Soni
 
PPT
Mesics lecture 8 arrays in 'c'
eShikshak
 
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
teddiyfentaw
 
Chapter-Five.pptx
berekethailu2
 
1-Intoduction ------------- Array in C++
ab6399671
 
CHAPTER-5.ppt
Tekle12
 
CSCI 238 Chapter 08 Arrays Textbook Slides
DanWooster1
 
Lecture 7
Mohammed Khan
 
Lecture 9
Mohammed Khan
 
Arrays_in_c++.pptx
MrMaster11
 
Array,string structures. Best presentation pptx
Kalkaye
 
Array In C++ programming object oriented programming
Ahmad177077
 
Arrays_and_Strings_in_C_Programming.pptx
samreenghauri786
 
Arrays and library functions
Swarup Kumar Boro
 
Arrays
ViniVini48
 
C++ Arrays
أحمد محمد
 
C++ Arrays
أحمد محمد
 
C96e1 session3 c++
Mukund Trivedi
 
Lec 25 - arrays-strings
Princess Sam
 
ARRAYS.pptx
MamataAnilgod
 
One dimensional arrays
Satyam Soni
 
Mesics lecture 8 arrays in 'c'
eShikshak
 
Ad

More from Tareq Hasan (20)

PDF
Caching in WordPress
Tareq Hasan
 
PDF
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
PDF
Composer - The missing package manager for PHP
Tareq Hasan
 
PDF
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
PPT
08 c++ Operator Overloading.ppt
Tareq Hasan
 
PPT
01 c++ Intro.ppt
Tareq Hasan
 
PPT
chapter22.ppt
Tareq Hasan
 
PPT
chapter - 6.ppt
Tareq Hasan
 
PPT
Algorithm.ppt
Tareq Hasan
 
PPT
chapter-8.ppt
Tareq Hasan
 
PPT
chapter23.ppt
Tareq Hasan
 
PPT
chapter24.ppt
Tareq Hasan
 
PPT
Algorithm: priority queue
Tareq Hasan
 
PPT
Algorithm: Quick-Sort
Tareq Hasan
 
PPT
Java: GUI
Tareq Hasan
 
PPT
Java: Inheritance
Tareq Hasan
 
PPT
Java: Exception
Tareq Hasan
 
PPT
Java: Introduction to Arrays
Tareq Hasan
 
PPT
Java: Class Design Examples
Tareq Hasan
 
PPT
Java: Objects and Object References
Tareq Hasan
 
Caching in WordPress
Tareq Hasan
 
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
Composer - The missing package manager for PHP
Tareq Hasan
 
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
08 c++ Operator Overloading.ppt
Tareq Hasan
 
01 c++ Intro.ppt
Tareq Hasan
 
chapter22.ppt
Tareq Hasan
 
chapter - 6.ppt
Tareq Hasan
 
Algorithm.ppt
Tareq Hasan
 
chapter-8.ppt
Tareq Hasan
 
chapter23.ppt
Tareq Hasan
 
chapter24.ppt
Tareq Hasan
 
Algorithm: priority queue
Tareq Hasan
 
Algorithm: Quick-Sort
Tareq Hasan
 
Java: GUI
Tareq Hasan
 
Java: Inheritance
Tareq Hasan
 
Java: Exception
Tareq Hasan
 
Java: Introduction to Arrays
Tareq Hasan
 
Java: Class Design Examples
Tareq Hasan
 
Java: Objects and Object References
Tareq Hasan
 

Recently uploaded (20)

PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PDF
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
infertility, types,causes, impact, and management
Ritu480198
 
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Horarios de distribución de agua en julio
pegazohn1978
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Introduction presentation of the patentbutler tool
MIPLM
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 

02 c++ Array Pointer

  • 1. Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3
  • 2. Objectives In this chapter, you will learn: How to use the address operator About arrays How to store values in an array How to access and use array values The value of using a constant to refer to an array’s size 3
  • 3. Objectives In this chapter, you will learn: Techniques to access some of the values in an array How to use parallel arrays How to use strings About special string-handling problems About pointers How to use a pointer in place of an array name 3
  • 4. Using the Address Operator A variable’s memory address is a fixed location; a variable’s address is a constant Although you cannot choose a variable’s actual memory address, you can examine it To do so, you use the address operator (&) The output is shown in Figure 3-2 The memory address is of not use to you at this point; you use the address operator merely as a curiosity The hexadecimal numbering system uses the values 0 through 9, and the letters a through f to represent the decimal values 0 through 15 3
  • 5. Using the Address Operator 3 F3-1.cpp //console I/O
  • 6. Using the Address Operator In the steps listed on pages 73 and 74 of the textbook, you will experiment with memory addresses in your computer system 3 F3-3.cpp & F3-4.cpp
  • 7. Understanding Arrays A list of individual items that all have the same type is called an array An array holds two or more variables with the same name and type in adjacent memory positions The variables with the same name are distinguished from one another by their subscripts; the subscript is a number that indicates the position of the particular array element being used Anytime you need many related variables, consider using an array 3
  • 8. Understanding Arrays In C++, you declare an array by using the form type arrayName [size]; where type is any simple type, arrayName is any legal identifier, and size (in the square bracket) represents the number of elements the array contains An element is a single object in an array An array name actually represents a memory address When you declare an array, you tell the compiler to use the array name to indicate the beginning address of a series of elements 3
  • 9. Understanding Arrays The subscript used to access an element of an array indicates how much to add to the starting address to locate a value 3
  • 10. Storing Values in an Array You most often create an array when you want to store a number of related variable elements When you declare an array like int array [4];, you set aside enough memory to hold four integers, but you say nothing about the values stored in those four memory locations The values are unknown—they are whatever was stored in those memory locations before the computer reserved the locations for use by your program Programmers often say that these memory locations are filled with garbage , or useless values 3
  • 11. Storing Values in an Array Just as you can initialize a single variable when you declare it, you can provide values for an array when you declare it The statement int rent[4] = {250, 375, 460, 600}; provides four values for the array If you declare an array without a size, but provide initialization values, C++ creates an array with the exact size you need If you do not provide enough values to fill an array, C++ fills any unassigned array elements with zeros 3
  • 12. Program that Uses Single and Array Variables 3 F3-6.cpp
  • 13. Accessing and Using Array Values Once an array is filled with values, you can access and use an individual array value in the same manner you would access and use any single variable of the same type If you need to access an element in an array, you can use the array name and a constant subscript such as 0 or 1 Alternately, you can use a variable as a subscript 3
  • 14. Accessing and Using Array Values The for loop prints arrayInt[0] through arrayInt[4] because x increases from 0 and remains less than 5 When the code in Figure 3-9 executes, the user will be prompted 10 times and allowed to enter a floating point value after each prompt The 10 values will be stored in price[0] through price[9], respectively 3
  • 15. Accessing and Using Array Values 3
  • 16. Using a Constant to Refer to an Array’s Size Often, using a for loop is a convenient way to access all array elements because arrays always have a specific, known size, and for loops execute a specific, known number of times When you want to access all array elements in sequential order, you can use a subscript that you vary from 0 to 1 less than the number of elements of the array Figure 3-10 shows a program that declares an array with 12 elements 3
  • 17. Using a Constant to Control Loops 3 F3-10.cpp
  • 18. Accessing Elements in an Array When you want to access a single array element, you use a subscript that indicates the position of the value you want to access When you want to access all of the elements in an array, a for loop usually is convenient The program in Figure 3-11 declares an array for 30 integer test scores, and single variables that serve as subscripts, a total, and the average A sentinel or dummy is any value that stops a loop’s execution You enter the program from Figure 3-11 and modify the program to better understand some of its properties and discover some of its flaws, using the procedures on pages 82 and 83 of the textbook 3
  • 19. A Program That Averages Up to 30 Test Scores 3 F3-11.cpp
  • 20. Using Parallel Arrays When you want to access an array element, you use the appropriate subscript If each array element’s position has a logical connection to the array value’s purpose, accessing an array value is a straightforward process Sometimes the numbers you need to access appropriate array values are not small whole numbers 3
  • 21. A Program That Determines Insurance Premiums 3 F3-12.cpp
  • 22. Using Parallel Arrays If you write a program in which you ask the user for a part number so that you can display the price, you cannot use the part number as a subscript to a price array unless you create a price array with at least 456 elements Creating an array with 456 elements that need to store four prices is cumbersome and inefficient 3
  • 23. Using Parallel Arrays A better solution is to create two arrays of just four elements each—one to hold the four part numbers, and one to hold the four prices that correspond to those part numbers Such corresponding arrays are called parallel arrays 3
  • 24. Program That Determines Part Prices 3 F3-14.cpp F3-14.cpp
  • 25. Using Parallel Arrays Create the program that determines the correct price number for a part, and then improve the program by following the instructions on pages 85 to 87 of the textbook 3
  • 26. Creating Arrays of Class Objects Just as you can create arrays of simple types such as int and double, you can create arrays of class objects The program in Figure 3-16 creates an array of four Automobile objects To access any individual class object field, you use the object’s individual name, including its subscript, followed by a dot and the field name 3
  • 27. Creating an Array of Class Objects 3 F3-15
  • 28. Output of Program from Figure 3-16 3
  • 29. Using Strings In C++, a character variable can hold a single character value, such as ‘A’ or ‘$’ Single character values are always expressed within single quotation marks In C++, if you want to express multiple character values, such as a first name or a book title, you use double quotation marks A C++ value expressed within double quotation marks is commonly called a string 3
  • 30. Using Strings You already have used strings with cout statements, as in cout<<“Hello”; Just as a value such as 14 is a numeric constant, a value such as “Hello” is referred to as a string constant In C++ an array of characters and a string are declared in the same way You might create an array of characters if you need to store six one-letter department codes, or five one-letter grades that can be assigned on a test 3
  • 31. Using Strings The null character is represented by the combination ‘\0’ (backslash and zero), or by using the constant NULL that is available if you use the statement #include,<iostream.h> at the top of any file you compile 3
  • 32. Special String Handling Problems String present some special handling problems When you use the cin statement with a string, cin stops adding characters to the string when it encounters white space Often, this means that cin stops when the user presses the Enter key But cin also stops when the user presses the spacebar or the Tab key 3
  • 33. A Program That Reads a Name 3
  • 34. Special String Handling Problems When the user types Mark Ann in the program in Figure 3-19, the cin statement accepts Mary into the string and leaves Ann waiting in an area called the input buffer If the program contains a subsequent cin statement, then Ann is accepted and assigned to the string named in the second cin statement 3
  • 36. Special String Handling Problems Another string handling problem occurs when you attempt to assign one string to another To assign the name of the clubPresident to the same name as the clubVicePresident, you must assign each character value in the clubVicePresident name to the corresponding character location in the clubPresident name A related string-handling problem occurs when you try to compare two strings 3
  • 37. Special String Handling Problems If you want to determine whether clubPresident and clubVicePresident have the same name, it might seem natural to write a statement such as: if(clubPresident == clubVicePresident) cout<<“They are the same”<<endl; You could write instructions to compare two strings by each character of one string to the corresponding character in the other string, such as in the following: if(clubPresident[0]==clubVicePresident[0] && clubPresident[1]==clubVicePresident[1]. . . 3
  • 38. Using the strcmp() Function 3 F3-23.cpp
  • 39. Special String Handling Problems You also can replace this tedious method with the built-in function strcmp( ) Declaring an array of strings poses a few special problems To solve them, you must learn to use a two-dimensional array 3
  • 40. Using Pointers You also can declare variables that can hold memory addresses These variables are called pointer variables, or simply pointers You declare a pointer with a type, just like other variables The major difference between using a pointer name and the address operator with a variable name is that a pointer is a variable 3
  • 41. Using a Pointer Instead of an Array Name Advanced C++ programmers use pointers for many purposes Sometimes they use a pointer as an alternative to an array name The program illustrated in Figure 3-25 shows four different ways to access the same seven values The program declares an integer array with sales figures for seven days for a small business The program also declares an integer pointer and assigns the address of the first sales figure to that pointer 3
  • 42. A Program That Uses Array and Pointer Notation 3 F3-25.cpp
  • 43. Output of Program From Figure 3-25 3
  • 44. Using Pointers to Hold Strings 3 F3-27.cpp
  • 45. Using a Pointer Instead of an Array Name Because pointers access computer memory locations, using pointers can be dangerous because you might point to an alter memory locations that you had no intention of altering A dangling reference is when you delete the value pointed to by one of the pointers, and the other pointer is left without a value 3