Chapter 1 – Introduction to Computers and C++ Programming

Download Report

Transcript Chapter 1 – Introduction to Computers and C++ Programming

CISC181 Introduction to
Computer Science
Dr. McCoy
Lecture 13
October 13, 2009
1
Repeated Slides
• Some of the following slides are repeated
from lecture 8 – character
strings/character arrays
2
Storing Strings in Character Arrays
• Character arrays may be initialized using a
string literal:
Char name[ ] = “Jane”;
Initializes the char array “name” to hold the
individual characters J-a-n-e plus a special
string termination character called the null
character writte ‘\0’
So, name is a 5 character array.
3
Strings in Character Arrays
• An alternative:
char name[ ] = {‘J’, ‘a’, ‘n’, ‘e’, ‘\0’};
• Common mistake – when using a char
array to hold strings, forgetting to leave the
extra spot for the null termination
character.
4
5
4.4
Examples Using Arrays
• Strings (more in ch. 5) KFM – note Ch 9 in
Savitch
– 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'
 2003 Prentice Hall, Inc. All rights reserved.
Reading Character Strings
• Character arrays input and output are
straightforward. Can read a character
string directly from the keyboard:
char last_name[20];
cin >> last_name;
NOTE: no indication last_name is an array in
the input statement!
NOTE: the read-in string must be at most 19
characters long else will have problems!
• Character array output:
cout << last_name;
6
7
4.4
Examples Using Arrays
• Input from keyboard
char string2[ 10 ];
cin >> string2;
– Puts user input in string
• Stops at first whitespace character
• Adds null character
– If too much text entered, data written beyond array
• We want to avoid this (section 5.12 explains how)
• Printing strings
– cout << string2 << endl;
• Does not work for other array types
– Characters printed until null found
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 4_12: fig04_12.cpp
// Treating character arrays as strings.
#include <iostream>
8
Outline
fig04_12.cpp
(1 of 2)
using std::cout;
using std::cin;
using std::endl;
Two different ways to declare
strings. string2 is
initialized, and its size
// determined
reserves 20
characters .
automatically
int main()
{
char string1[ 20 ],
char string2[] = "string literal"; // reserves 15 characters
// read string
cout << "Enter
cin >> string1;
Examples of reading strings
fromstring2
the keyboard and
from user into array
the string \"helloprinting
there\":
";out.
them
// reads "hello" [space terminates input]
// output strings
cout << "string1 is: " << string1
<< "\nstring2 is: " << string2;
cout << "\nstring1 with spaces between characters is:\n";
 2003 Prentice Hall, Inc.
All rights reserved.
24
25
26
27
28
29
30
31
32
33
// output characters until null character is reached
for ( int i = 0; string1[ i ] != '\0'; i++ )
cout << string1[ i ] << ' ';
9
Outline
Can access the characters in a fig04_12.cpp
using array notation.
(2 of 2)
The loop ends when the null
character is found.
fig04_12.cpp
termination
output (1 of 1)
cin >> string1; // reads "there"
string
cout << "\nstring1 is: " << string1 << endl;
return 0;
// indicates successful
} // 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
 2003 Prentice Hall, Inc.
All rights reserved.
Some recursive functions with
arrays
• From D&D 4.37 – Printing a string
backwards.
• Write a recursive function stringReverse
that takes a character array containing a
string as an argument, prints the string
backwards, and returns nothing. The
function should stop processing and return
when the terminating null character is
encountered.
10
Palindromes (D&D 4.32)
• A pelindrome is a string that is spelled the
same way forwards and backwards. Some
examples of palindromes are “radar”, “able
was I ere I saw elba” (if blanks are
ignored), “billib”, and “a man a plan a
canal panama” (if blanks are ignored).
11
• Write a recursive function testPalindrome
that returns true if the string stored in the
array is a palindrome, and false otherwise.
• The function should take 3 arguments – a
(const) character array, the index to the
left end of the string, the index to the right
end of the string.
12
• Can you write a main program that will
enable this function to be used when the
string read in actually contains spaces?
13
BinarySearch D&D 4.34
14
4.8 Searching Arrays: Linear
Search and Binary 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
15
4.8 Searching Arrays: Linear
Search and Binary Search
• 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
N
– Repeat search on last half
5
– Very fast
16
• At most N steps, where 2 > # of elements
• 30 element array takes at most 5 steps
Arguments to Binary Search
•
•
•
•
The (const) array to be searched
The key (value) to look for
Low_index
High_index
17
•
•
•
•
•
•
•
•
•
•
Example
A[0] = 1
A[1] = 2
A[2] = 4
A[3] = 8
A[4] = 16
A[5] = 32
A[6] = 64
A[7] = 128
A[8] = 256
A[9] = 512
18
SelectionSort D&D 4.31
• A selection sort searches an array looking
for the smallest element in the array.
Then, the smallest element is swapped
with the first element of the array. The
process is repeated for the subarray
beginning with the second element of the
array.
19
• Each pass of the array results in one
element being placed in its proper
location.
void SelectionSort(int arr[], int size);
// takes an integer array and its size
// sorts the array using the selection
// sort algorithm
20
• This sort performs comparably to the
bubble sort – for an array of n elements, n1 passes must be made, and for each
subarray, n-1 comparisons must be made
to find the smallest value. When the
subarray being processed contains one
element, the array is sorted.
21