SlideShare a Scribd company logo
EC-102 Computer System &
Programming
Lecture #9
Instructor: Jahan Zeb
Department of Computer Engineering (DCE)
College of E&ME
Searching Arrays: Linear Search
 Search array for a key value
 Linear search
– Compare each element of array with key value
• Start at one end, go to other
– Useful for small and unsorted arrays
• Inefficient
• If search key not present, examines every element
1 // Fig. 4.19: fig04_19.cpp
2 // Linear search of an array.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int linearSearch( const int [], int, int ); // prototype
10
11 int main()
12 {
13 const int arraySize = 100; // size of array a
14 int a[ arraySize ]; // create array a
15 int searchKey; // value to locate in a
16
17 for ( int i = 0; i < arraySize; i++ ) // create some data
18 a[ i ] = 2 * i;
19
20 cout << "Enter integer search key: ";
21 cin >> searchKey;
22
23 // attempt to locate searchKey in array a
24 int element = linearSearch( a, searchKey, arraySize );
25
Takes array, search key, and
array size.
26 // display results
27 if ( element != -1 )
28 cout << "Found value in location " << element << endl;
29 else
30 cout << "Value not found" << endl;
31
32 return 0; // indicates successful termination
33
34 } // end main
35
36 // compare key to every element of array until location is
37 // found or until end of array is reached; return subscript of
38 // element if key or -1 if key not found
39 int linearSearch( const int array[], int key, int sizeOfArray )
40 {
41 for ( int j = 0; j < sizeOfArray; j++ )
42
43 if ( array[ j ] == key ) // if found,
44 return j; // return location of key
45
46 return -1; // key not found
47
48 } // end function linearSearch
Enter integer search key: 36
Found value in location 18
Enter integer search key: 37
Value not found
Multiple-Subscripted Arrays
 Multiple subscripts
– a[ i ][ j ]
– Tables with rows and columns
– Specify row, then column
– “Array of arrays”
• a[0] is an array of 4 elements
• a[0][0] is the first element of that array
Row 0
Row 1
Row 2
Column 0 Column 1 Column 2 Column 3
a[ 0 ][ 0 ]
a[ 1 ][ 0 ]
a[ 2 ][ 0 ]
a[ 0 ][ 1 ]
a[ 1 ][ 1 ]
a[ 2 ][ 1 ]
a[ 0 ][ 2 ]
a[ 1 ][ 2 ]
a[ 2 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 3 ]
a[ 2 ][ 3 ]
Row subscript
Array name
Column subscript
Multiple-Subscripted Arrays
 To initialize
– Default of 0
– Initializers grouped by row in braces
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
1 2
3 4
1 0
3 4
Row 0 Row 1
Multiple-Subscripted Arrays
 Referenced like normal
cout << b[ 0 ][ 1 ];
– Outputs 0
– Cannot reference using commas
cout << b[ 0, 1 ];
• Syntax error
 Function prototypes
– Must specify sizes of subscripts
• First subscript not necessary, as with single-scripted arrays
– void printArray( int [][ 3 ] );
1 0
3 4
1 // Fig. 4.22: fig04_22.cpp
2 // Initializing multidimensional arrays.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 void printArray( int [][ 3 ] );
9
10 int main()
11 {
12 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
13 int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
14 int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
15
16 cout << "Values in array1 by row are:" << endl;
17 printArray( array1 );
18
19 cout << "Values in array2 by row are:" << endl;
20 printArray( array2 );
21
22 cout << "Values in array3 by row are:" << endl;
23 printArray( array3 );
24
25 return 0; // indicates successful termination
26
27 } // end main
Note the various initialization
styles. The elements in
array2 are assigned to the
first row and then the second.
Note the format of the
prototype.
28
29 // function to output array with two rows and three columns
30 void printArray( int a[][ 3 ] )
31 {
32 for ( int i = 0; i < 2; i++ ) { // for each row
33
34 for ( int j = 0; j < 3; j++ ) // output column values
35 cout << a[ i ][ j ] << ' ';
36
37 cout << endl; // start new line of output
38
39 } // end outer for structure
40
41 } // end function printArray
Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0
For loops are often used to
iterate through arrays. Nested
loops are helpful with
multiple-subscripted arrays.
Character Arrays
 Strings
 Arrays of characters
– All strings end with null ('0')
– Examples
• char string1[] = "hello";
– Null character implicitly added
– string1 has 6 elements
• char string1[] = { 'h', 'e', 'l', 'l',
'o', '0’ };
– Subscripting is the same
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'
Examples Using Arrays
 Input from keyboard
char string2[ 10 ];
cin >> string2;
– Puts user input in string
• Stops at first whitespace character
• Adds null character
 Printing strings
– cout << string2 << endl;
• Does not work for other array types
– Characters printed until null found
1 // Fig. 4_12: fig04_12.cpp
2 // Treating character arrays as strings.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 char string1[ 20 ], // reserves 20 characters
12 char string2[] = "string literal"; // reserves 15 characters
13
14 // read string from user into array string2
15 cout << "Enter the string "hello there": ";
16 cin >> string1; // reads "hello" [space terminates input]
17
18 // output strings
19 cout << "string1 is: " << string1
20 << "nstring2 is: " << string2;
21
22 cout << "nstring1 with spaces between characters is:n";
23
Two different ways to declare
strings. string2 is
initialized, and its size
determined automatically .
Examples of reading strings
from the keyboard and
printing them out.
24 // output characters until null character is reached
25 for ( int i = 0; string1[ i ] != '0'; i++ )
26 cout << string1[ i ] << ' ';
27
28 cin >> string1; // reads "there"
29 cout << "nstring1 is: " << string1 << endl;
30
31 return 0; // indicates successful termination
32
33 } // end main
Enter the string "hello there": hello there
string1 is: hello
string2 is: string literal
string1 with spaces between characters is:
h e l l o
string1 is: there
Can access the characters in a
string using array notation.
The loop ends when the null
character is found.
Pointers
 Pointers
– Powerful, but difficult to master
– Simulate pass-by-reference
– Close relationship with arrays and strings
Pointer Variable Declarations and
Initialization
 Pointer variables
– Contain memory addresses as values
– Normally, variable contains specific value (direct reference)
– Pointers contain address of variable that has specific value
(indirect reference)
 Indirection
– Referencing value through pointer
 Pointer declarations
– * indicates variable is pointer
int *myPtr;
declares pointer to int, pointer of type int *
– Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
count
7
countPtr
count
7
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
yPtr
y
5
yptr
500000 600000
y
600000 5
address of y
is value of
yptr
Pointer Operators
 * (indirection/dereferencing operator)
– Returns synonym for object its pointer operand points to
– *yPtr returns y (because yPtr points to y).
*yptr = 9; // assigns 9 to y
 * and & are inverses of each other
1 // Fig. 5.4: fig05_04.cpp
2 // Using the & and * operators.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 int a; // a is an integer
11 int *aPtr; // aPtr is a pointer to an integer
12
13 a = 7;
14 aPtr = &a; // aPtr assigned address of a
15
16 cout << "The address of a is " << &a
17 << "nThe value of aPtr is " << aPtr;
18
19 cout << "nnThe value of a is " << a
20 << "nThe value of *aPtr is " << *aPtr;
21
22 cout << "nnShowing that * and & are inverses of "
23 << "each other.n&*aPtr = " << &*aPtr
24 << "n*&aPtr = " << *&aPtr << endl;
25
* and & are inverses
of each other
26 return 0; // indicates successful termination
27
28 } // end main
The address of a is 0012FED4
The value of aPtr is 0012FED4
The value of a is 7
The value of *aPtr is 7
Showing that * and & are inverses of each other.
&*aPtr = 0012FED4
*&aPtr = 0012FED4
* and & are inverses; same
result when both applied to
aPtr
Calling Functions by Reference
 3 ways to pass arguments to function
– Pass-by-value
– Pass-by-reference with reference arguments
– Pass-by-reference with pointer arguments
 return can return one value from function
 Arguments passed to function using reference
arguments
– Modify original values of arguments
– More than one value “returned”
Calling Functions by Reference
 Pass-by-reference with pointer arguments
– Simulate pass-by-reference
• Use pointers and indirection operator
– Pass address of argument using & operator
– Arrays not passed with & because array name already pointer
– * operator used as alias/nickname for variable inside of
function
1 // Fig. 5.6: fig05_06.cpp
2 // Cube a variable using pass-by-value.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int cubeByValue( int ); // prototype
9
10 int main()
11 {
12 int number = 5;
13
14 cout << "The original value of number is " << number;
15
16 // pass number by value to cubeByValue
17 number = cubeByValue( number );
18
19 cout << "nThe new value of number is " << number << endl;
20
21 return 0; // indicates successful termination
22
23 } // end main
24
Pass number by value; result
returned by
cubeByValue
25 // calculate and return cube of integer argument
26 int cubeByValue( int n )
27 {
28 return n * n * n; // cube local variable n and return result
29
30 } // end function cubeByValue
The original value of number is 5
The new value of number is 125
cubeByValue receives
parameter passed-by-value
Cubes and returns
local variable n
1 // Fig. 5.7: fig05_07.cpp
2 // Cube a variable using pass-by-reference
3 // with a pointer argument.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 void cubeByReference( int * ); // prototype
10
11 int main()
12 {
13 int number = 5;
14
15 cout << "The original value of number is " << number;
16
17 // pass address of number to cubeByReference
18 cubeByReference( &number );
19
20 cout << "nThe new value of number is " << number << endl;
21
22 return 0; // indicates successful termination
23
24 } // end main
25
Apply address operator & to
pass address of number to
cubeByReference
cubeByReference
modified variable
number
Prototype indicates parameter
is pointer to int
26 // calculate cube of *nPtr; modifies variable number in main
27 void cubeByReference( int *nPtr )
28 {
29 *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr
30
31 } // end function cubeByReference
The original value of number is 5
The new value of number is 125
cubeByReference
receives address of int
variable,
i.e., pointer to an int
Modify and access int
variable using indirection
operator *

More Related Content

What's hot

Pointers
PointersPointers
Pointers
sanya6900
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
Vishalini Mugunen
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
Dharma Kshetri
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
HNDE Labuduwa Galle
 
Dd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionsDd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionstemkin abdlkader
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
C++ ch2
C++ ch2C++ ch2
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
C++
C++C++
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
khush_boo31
 
Advanced C - Part 3
Advanced C - Part 3Advanced C - Part 3
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
Aditya Nihal Kumar Singh
 
Functions in C
Functions in CFunctions in C
Functions in C
Princy Nelson
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
Vaishnavee Sharma
 

What's hot (20)

Pointers
PointersPointers
Pointers
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
 
Dd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionsDd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functions
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
C++ ch2
C++ ch2C++ ch2
C++ ch2
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
C++
C++C++
C++
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
Advanced C - Part 3
Advanced C - Part 3Advanced C - Part 3
Advanced C - Part 3
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 

Viewers also liked

c++ Project list
c++ Project list c++ Project list
c++ Project list
NUST Stuff
 
El Arandano
El ArandanoEl Arandano
El Arandano
kathiacarlos
 
концепція.нова школа
концепція.нова школаконцепція.нова школа
концепція.нова школа
Виталий Базаль
 
Lesson 1 matrix
Lesson 1 matrixLesson 1 matrix
Lesson 1 matrix
Melvy Dela Torre
 
Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105
NUST Stuff
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computing
NUST Stuff
 
Chapter 02 using drawing tools
Chapter 02 using drawing toolsChapter 02 using drawing tools
Chapter 02 using drawing tools
Melvy Dela Torre
 
Bank of india
Bank of indiaBank of india
Bank of india
Ravi kumar
 
Chap 8 thiols and sulfides (1)
Chap 8 thiols and sulfides (1)Chap 8 thiols and sulfides (1)
Chap 8 thiols and sulfides (1)
Melvy Dela Torre
 
Engineering Drawing: Chapter 08 orthographic convention
Engineering Drawing: Chapter 08 orthographic conventionEngineering Drawing: Chapter 08 orthographic convention
Engineering Drawing: Chapter 08 orthographic conventionmokhtar
 
Engineering Drawing: Chapter 02 using drawing tools
Engineering Drawing: Chapter 02 using drawing toolsEngineering Drawing: Chapter 02 using drawing tools
Engineering Drawing: Chapter 02 using drawing toolsmokhtar
 
Engineering Drawing: Chapter 04 orthographic writing
Engineering Drawing: Chapter 04 orthographic writingEngineering Drawing: Chapter 04 orthographic writing
Engineering Drawing: Chapter 04 orthographic writingmokhtar
 
Handout # 6 pointers and recursion in c++
Handout # 6   pointers and recursion in c++Handout # 6   pointers and recursion in c++
Handout # 6 pointers and recursion in c++
NUST Stuff
 

Viewers also liked (20)

c++ Project list
c++ Project list c++ Project list
c++ Project list
 
Cert Bus II
Cert Bus IICert Bus II
Cert Bus II
 
RecruitingCampaign-Deck v6
RecruitingCampaign-Deck v6RecruitingCampaign-Deck v6
RecruitingCampaign-Deck v6
 
El Arandano
El ArandanoEl Arandano
El Arandano
 
Drawing chapter 02 using drawing tools 1
Drawing chapter 02 using drawing tools 1Drawing chapter 02 using drawing tools 1
Drawing chapter 02 using drawing tools 1
 
концепція.нова школа
концепція.нова школаконцепція.нова школа
концепція.нова школа
 
Lesson 1 matrix
Lesson 1 matrixLesson 1 matrix
Lesson 1 matrix
 
Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computing
 
Chapter 02 using drawing tools
Chapter 02 using drawing toolsChapter 02 using drawing tools
Chapter 02 using drawing tools
 
Bank of india
Bank of indiaBank of india
Bank of india
 
Drawing chapter 03 orthographic projection (1)
Drawing chapter 03 orthographic projection (1)Drawing chapter 03 orthographic projection (1)
Drawing chapter 03 orthographic projection (1)
 
Fluidmechanics
Fluidmechanics Fluidmechanics
Fluidmechanics
 
Dynamic behavior of catalytic converters
Dynamic behavior of catalytic convertersDynamic behavior of catalytic converters
Dynamic behavior of catalytic converters
 
Chapter 05 pictorial sketching
Chapter 05 pictorial sketchingChapter 05 pictorial sketching
Chapter 05 pictorial sketching
 
Chap 8 thiols and sulfides (1)
Chap 8 thiols and sulfides (1)Chap 8 thiols and sulfides (1)
Chap 8 thiols and sulfides (1)
 
Engineering Drawing: Chapter 08 orthographic convention
Engineering Drawing: Chapter 08 orthographic conventionEngineering Drawing: Chapter 08 orthographic convention
Engineering Drawing: Chapter 08 orthographic convention
 
Engineering Drawing: Chapter 02 using drawing tools
Engineering Drawing: Chapter 02 using drawing toolsEngineering Drawing: Chapter 02 using drawing tools
Engineering Drawing: Chapter 02 using drawing tools
 
Engineering Drawing: Chapter 04 orthographic writing
Engineering Drawing: Chapter 04 orthographic writingEngineering Drawing: Chapter 04 orthographic writing
Engineering Drawing: Chapter 04 orthographic writing
 
Handout # 6 pointers and recursion in c++
Handout # 6   pointers and recursion in c++Handout # 6   pointers and recursion in c++
Handout # 6 pointers and recursion in c++
 

Similar to Lecture#9 Arrays in c++

Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
JumanneChiyanda
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
GC University Faisalabad
 
pointers
pointerspointers
pointers
teach4uin
 
Arrays 06.ppt
Arrays 06.pptArrays 06.ppt
Arrays 06.ppt
ahtishamtariq511
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Kashif Nawab
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
lecture7.ppt
lecture7.pptlecture7.ppt
lecture7.ppt
EdFeranil
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
UmairMughal74
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
iammukesh1075
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Pointers and arrays
Pointers and arraysPointers and arrays
Pointers and arrays
Bhuvana Gowtham
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
yamew16788
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
kinan keshkeh
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
ShivamChaturvedi67
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
Mrhaider4
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 

Similar to Lecture#9 Arrays in c++ (20)

Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Pointers
PointersPointers
Pointers
 
pointers
pointerspointers
pointers
 
Arrays 06.ppt
Arrays 06.pptArrays 06.ppt
Arrays 06.ppt
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Array assignment
Array assignmentArray assignment
Array assignment
 
lecture7.ppt
lecture7.pptlecture7.ppt
lecture7.ppt
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Pointers and arrays
Pointers and arraysPointers and arrays
Pointers and arrays
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 

More from NUST Stuff

Me211 1
Me211 1Me211 1
Me211 1
NUST Stuff
 
Lab LCA 1 7
Lab LCA 1 7Lab LCA 1 7
Lab LCA 1 7
NUST Stuff
 
Me211 4
Me211 4Me211 4
Me211 4
NUST Stuff
 
Me211 3
Me211 3Me211 3
Me211 3
NUST Stuff
 
Drag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluidDrag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluid
NUST Stuff
 
Nums entry test 2017 paper
Nums entry test 2017 paperNums entry test 2017 paper
Nums entry test 2017 paper
NUST Stuff
 
Nums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bdsNums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bds
NUST Stuff
 
MCAT Full length paper 8-student_copy_
MCAT Full length paper  8-student_copy_MCAT Full length paper  8-student_copy_
MCAT Full length paper 8-student_copy_
NUST Stuff
 
MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_
NUST Stuff
 
MCAT Full length paper 6-student_copy_
MCAT Full length paper  6-student_copy_MCAT Full length paper  6-student_copy_
MCAT Full length paper 6-student_copy_
NUST Stuff
 
MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_
NUST Stuff
 
Mcat (original paper 2014)
Mcat (original paper 2014)Mcat (original paper 2014)
Mcat (original paper 2014)
NUST Stuff
 
MCAT Full length paper 4-student_copy
MCAT Full length paper  4-student_copyMCAT Full length paper  4-student_copy
MCAT Full length paper 4-student_copy
NUST Stuff
 
mcat (original paper 2013)
mcat (original paper 2013)mcat (original paper 2013)
mcat (original paper 2013)
NUST Stuff
 
mcat (original paper 2012)
mcat (original paper 2012)mcat (original paper 2012)
mcat (original paper 2012)
NUST Stuff
 
MCAT Full length paper 3 final
MCAT Full length paper 3 finalMCAT Full length paper 3 final
MCAT Full length paper 3 final
NUST Stuff
 
MCAT (original paper 2011)
MCAT (original paper 2011)MCAT (original paper 2011)
MCAT (original paper 2011)
NUST Stuff
 
mcat (original paper 2010)
 mcat (original paper 2010) mcat (original paper 2010)
mcat (original paper 2010)
NUST Stuff
 
MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)
NUST Stuff
 

More from NUST Stuff (20)

Me211 1
Me211 1Me211 1
Me211 1
 
Lab LCA 1 7
Lab LCA 1 7Lab LCA 1 7
Lab LCA 1 7
 
Me211 2
Me211 2Me211 2
Me211 2
 
Me211 4
Me211 4Me211 4
Me211 4
 
Me211 3
Me211 3Me211 3
Me211 3
 
Drag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluidDrag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluid
 
Nums entry test 2017 paper
Nums entry test 2017 paperNums entry test 2017 paper
Nums entry test 2017 paper
 
Nums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bdsNums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bds
 
MCAT Full length paper 8-student_copy_
MCAT Full length paper  8-student_copy_MCAT Full length paper  8-student_copy_
MCAT Full length paper 8-student_copy_
 
MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_
 
MCAT Full length paper 6-student_copy_
MCAT Full length paper  6-student_copy_MCAT Full length paper  6-student_copy_
MCAT Full length paper 6-student_copy_
 
MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_
 
Mcat (original paper 2014)
Mcat (original paper 2014)Mcat (original paper 2014)
Mcat (original paper 2014)
 
MCAT Full length paper 4-student_copy
MCAT Full length paper  4-student_copyMCAT Full length paper  4-student_copy
MCAT Full length paper 4-student_copy
 
mcat (original paper 2013)
mcat (original paper 2013)mcat (original paper 2013)
mcat (original paper 2013)
 
mcat (original paper 2012)
mcat (original paper 2012)mcat (original paper 2012)
mcat (original paper 2012)
 
MCAT Full length paper 3 final
MCAT Full length paper 3 finalMCAT Full length paper 3 final
MCAT Full length paper 3 final
 
MCAT (original paper 2011)
MCAT (original paper 2011)MCAT (original paper 2011)
MCAT (original paper 2011)
 
mcat (original paper 2010)
 mcat (original paper 2010) mcat (original paper 2010)
mcat (original paper 2010)
 
MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)
 

Recently uploaded

Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 

Recently uploaded (20)

Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 

Lecture#9 Arrays in c++

  • 1. EC-102 Computer System & Programming Lecture #9 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME
  • 2. Searching Arrays: Linear Search  Search array for a key value  Linear search – Compare each element of array with key value • Start at one end, go to other – Useful for small and unsorted arrays • Inefficient • If search key not present, examines every element
  • 3. 1 // Fig. 4.19: fig04_19.cpp 2 // Linear search of an array. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int linearSearch( const int [], int, int ); // prototype 10 11 int main() 12 { 13 const int arraySize = 100; // size of array a 14 int a[ arraySize ]; // create array a 15 int searchKey; // value to locate in a 16 17 for ( int i = 0; i < arraySize; i++ ) // create some data 18 a[ i ] = 2 * i; 19 20 cout << "Enter integer search key: "; 21 cin >> searchKey; 22 23 // attempt to locate searchKey in array a 24 int element = linearSearch( a, searchKey, arraySize ); 25 Takes array, search key, and array size.
  • 4. 26 // display results 27 if ( element != -1 ) 28 cout << "Found value in location " << element << endl; 29 else 30 cout << "Value not found" << endl; 31 32 return 0; // indicates successful termination 33 34 } // end main 35 36 // compare key to every element of array until location is 37 // found or until end of array is reached; return subscript of 38 // element if key or -1 if key not found 39 int linearSearch( const int array[], int key, int sizeOfArray ) 40 { 41 for ( int j = 0; j < sizeOfArray; j++ ) 42 43 if ( array[ j ] == key ) // if found, 44 return j; // return location of key 45 46 return -1; // key not found 47 48 } // end function linearSearch
  • 5. Enter integer search key: 36 Found value in location 18 Enter integer search key: 37 Value not found
  • 6. Multiple-Subscripted Arrays  Multiple subscripts – a[ i ][ j ] – Tables with rows and columns – Specify row, then column – “Array of arrays” • a[0] is an array of 4 elements • a[0][0] is the first element of that array Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript
  • 7. Multiple-Subscripted Arrays  To initialize – Default of 0 – Initializers grouped by row in braces int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 2 3 4 1 0 3 4 Row 0 Row 1
  • 8. Multiple-Subscripted Arrays  Referenced like normal cout << b[ 0 ][ 1 ]; – Outputs 0 – Cannot reference using commas cout << b[ 0, 1 ]; • Syntax error  Function prototypes – Must specify sizes of subscripts • First subscript not necessary, as with single-scripted arrays – void printArray( int [][ 3 ] ); 1 0 3 4
  • 9. 1 // Fig. 4.22: fig04_22.cpp 2 // Initializing multidimensional arrays. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 void printArray( int [][ 3 ] ); 9 10 int main() 11 { 12 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; 13 int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; 14 int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; 15 16 cout << "Values in array1 by row are:" << endl; 17 printArray( array1 ); 18 19 cout << "Values in array2 by row are:" << endl; 20 printArray( array2 ); 21 22 cout << "Values in array3 by row are:" << endl; 23 printArray( array3 ); 24 25 return 0; // indicates successful termination 26 27 } // end main Note the various initialization styles. The elements in array2 are assigned to the first row and then the second. Note the format of the prototype.
  • 10. 28 29 // function to output array with two rows and three columns 30 void printArray( int a[][ 3 ] ) 31 { 32 for ( int i = 0; i < 2; i++ ) { // for each row 33 34 for ( int j = 0; j < 3; j++ ) // output column values 35 cout << a[ i ][ j ] << ' '; 36 37 cout << endl; // start new line of output 38 39 } // end outer for structure 40 41 } // end function printArray Values in array1 by row are: 1 2 3 4 5 6 Values in array2 by row are: 1 2 3 4 5 0 Values in array3 by row are: 1 2 0 4 0 0 For loops are often used to iterate through arrays. Nested loops are helpful with multiple-subscripted arrays.
  • 11. Character Arrays  Strings  Arrays of characters – All strings end with null ('0') – Examples • char string1[] = "hello"; – Null character implicitly added – string1 has 6 elements • char string1[] = { 'h', 'e', 'l', 'l', 'o', '0’ }; – Subscripting is the same String1[ 0 ] is 'h' string1[ 2 ] is 'l'
  • 12. Examples Using Arrays  Input from keyboard char string2[ 10 ]; cin >> string2; – Puts user input in string • Stops at first whitespace character • Adds null character  Printing strings – cout << string2 << endl; • Does not work for other array types – Characters printed until null found
  • 13. 1 // Fig. 4_12: fig04_12.cpp 2 // Treating character arrays as strings. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int main() 10 { 11 char string1[ 20 ], // reserves 20 characters 12 char string2[] = "string literal"; // reserves 15 characters 13 14 // read string from user into array string2 15 cout << "Enter the string "hello there": "; 16 cin >> string1; // reads "hello" [space terminates input] 17 18 // output strings 19 cout << "string1 is: " << string1 20 << "nstring2 is: " << string2; 21 22 cout << "nstring1 with spaces between characters is:n"; 23 Two different ways to declare strings. string2 is initialized, and its size determined automatically . Examples of reading strings from the keyboard and printing them out.
  • 14. 24 // output characters until null character is reached 25 for ( int i = 0; string1[ i ] != '0'; i++ ) 26 cout << string1[ i ] << ' '; 27 28 cin >> string1; // reads "there" 29 cout << "nstring1 is: " << string1 << endl; 30 31 return 0; // indicates successful termination 32 33 } // end main Enter the string "hello there": hello there string1 is: hello string2 is: string literal string1 with spaces between characters is: h e l l o string1 is: there Can access the characters in a string using array notation. The loop ends when the null character is found.
  • 15. Pointers  Pointers – Powerful, but difficult to master – Simulate pass-by-reference – Close relationship with arrays and strings
  • 16. Pointer Variable Declarations and Initialization  Pointer variables – Contain memory addresses as values – Normally, variable contains specific value (direct reference) – Pointers contain address of variable that has specific value (indirect reference)  Indirection – Referencing value through pointer  Pointer declarations – * indicates variable is pointer int *myPtr; declares pointer to int, pointer of type int * – Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; count 7 countPtr count 7
  • 17. 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
  • 18. 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 yPtr y 5 yptr 500000 600000 y 600000 5 address of y is value of yptr
  • 19. Pointer Operators  * (indirection/dereferencing operator) – Returns synonym for object its pointer operand points to – *yPtr returns y (because yPtr points to y). *yptr = 9; // assigns 9 to y  * and & are inverses of each other
  • 20. 1 // Fig. 5.4: fig05_04.cpp 2 // Using the & and * operators. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int a; // a is an integer 11 int *aPtr; // aPtr is a pointer to an integer 12 13 a = 7; 14 aPtr = &a; // aPtr assigned address of a 15 16 cout << "The address of a is " << &a 17 << "nThe value of aPtr is " << aPtr; 18 19 cout << "nnThe value of a is " << a 20 << "nThe value of *aPtr is " << *aPtr; 21 22 cout << "nnShowing that * and & are inverses of " 23 << "each other.n&*aPtr = " << &*aPtr 24 << "n*&aPtr = " << *&aPtr << endl; 25 * and & are inverses of each other
  • 21. 26 return 0; // indicates successful termination 27 28 } // end main The address of a is 0012FED4 The value of aPtr is 0012FED4 The value of a is 7 The value of *aPtr is 7 Showing that * and & are inverses of each other. &*aPtr = 0012FED4 *&aPtr = 0012FED4 * and & are inverses; same result when both applied to aPtr
  • 22. Calling Functions by Reference  3 ways to pass arguments to function – Pass-by-value – Pass-by-reference with reference arguments – Pass-by-reference with pointer arguments  return can return one value from function  Arguments passed to function using reference arguments – Modify original values of arguments – More than one value “returned”
  • 23. Calling Functions by Reference  Pass-by-reference with pointer arguments – Simulate pass-by-reference • Use pointers and indirection operator – Pass address of argument using & operator – Arrays not passed with & because array name already pointer – * operator used as alias/nickname for variable inside of function
  • 24. 1 // Fig. 5.6: fig05_06.cpp 2 // Cube a variable using pass-by-value. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int cubeByValue( int ); // prototype 9 10 int main() 11 { 12 int number = 5; 13 14 cout << "The original value of number is " << number; 15 16 // pass number by value to cubeByValue 17 number = cubeByValue( number ); 18 19 cout << "nThe new value of number is " << number << endl; 20 21 return 0; // indicates successful termination 22 23 } // end main 24 Pass number by value; result returned by cubeByValue
  • 25. 25 // calculate and return cube of integer argument 26 int cubeByValue( int n ) 27 { 28 return n * n * n; // cube local variable n and return result 29 30 } // end function cubeByValue The original value of number is 5 The new value of number is 125 cubeByValue receives parameter passed-by-value Cubes and returns local variable n
  • 26. 1 // Fig. 5.7: fig05_07.cpp 2 // Cube a variable using pass-by-reference 3 // with a pointer argument. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 void cubeByReference( int * ); // prototype 10 11 int main() 12 { 13 int number = 5; 14 15 cout << "The original value of number is " << number; 16 17 // pass address of number to cubeByReference 18 cubeByReference( &number ); 19 20 cout << "nThe new value of number is " << number << endl; 21 22 return 0; // indicates successful termination 23 24 } // end main 25 Apply address operator & to pass address of number to cubeByReference cubeByReference modified variable number Prototype indicates parameter is pointer to int
  • 27. 26 // calculate cube of *nPtr; modifies variable number in main 27 void cubeByReference( int *nPtr ) 28 { 29 *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr 30 31 } // end function cubeByReference The original value of number is 5 The new value of number is 125 cubeByReference receives address of int variable, i.e., pointer to an int Modify and access int variable using indirection operator *