·
Arrays – Used to
process a collection of data all of which is of the same type.
o
Declaration
Examples
const int NUMBER_OF_EMPLOYEES = 150;
int employees[NUMBER_OF_EMPLOYEES];
int students[25];
double numbers[] = {5.6, 2.56, 3.14,
6};
char firstName[] = {‘J’, ‘o’, ‘e’,
‘\0’};
char lastName[] = “Russell”;
o
Usage Examples
cout << "The first letter in my name is " << firstName[0] << endl;
cout << "My name is " << firstName << " " << lastName << endl;
cout << "Enter new last name: ";
cin >> lastName;
firstName[0] = 'M';
cout << "My name is " << firstName << " " << lastName << endl;
// Good output
The first letter in my name is J
My name is Joe Russell
Enter new last name: Smith
My name is Moe Smith
// Bad output due to overstepping the bounds of the “lastName” array
The first letter in my name is J
My name is Joe Russell
Enter new last name: Sanderson
My name is M SandersoM
o
Arrays In
Functions
§
Function
Prototype Example
int processNumbers(int numbers[]);
int findGridLocation(int
gridLocations[][100]);
§
Example for
passing an entire array to a function.
const int NUMBER_OF_STUDENTS =
25;
int grades[NUMBER_OF_STUDENTS];
//
Code for filling in the student grades goes here
//
Here is the prototype to calculate the average
double
average(const int grades[], const int totalGrades);
// Note:
Use const to make sure that there are no
//
changes made to the grades array or totalGrades.
//
Call the function as follows
double classAverage;
classAverage = average(grades, NUMBER_OF_STUDENTS);
o
Multidimensional
Arrays – Arrays of more than one dimension
§
A Two Dimensional
Array can be thought of as an array of arrays.
The same logic can be applied for arrays of higher dimension.
//
Declaration Examples
int numbers[3][4]; // Three rows by four columns
int someMatrix[][3] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
char
somePlaces[][50] = { "
"
"
//
Usage Examples
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
cout << "someMatrix[" << i << "][" << j <<"] is "
<< someMatrix[i][j] << endl;
}
for(int k = 0; k < 3; k++)
cout << "The location is " << somePlaces[k] << endl;
// Good output
someMatrix[0][0] is 1
someMatrix[0][1] is 2
someMatrix[0][2] is 3
someMatrix[1][0] is 4
someMatrix[1][1] is 5
someMatrix[1][2] is 6
someMatrix[2][0] is 7
someMatrix[2][1] is 8
someMatrix[2][2] is 9
The location is
The location is
The location is
·
Strings –
Supports the C Programming way of representing strings and a C++ programming
string handling facility.
o
We call an array
of characters a C-string variable and an array of characters terminated by NULL
a C-string
o
The NULL
character in a C-string is used to determine the actual ending of the
string. The NULL character does not get
counted when determining the length of a C-string
o
Some useful
<ctype> predefined C-string functions:
|
PREDEFINED C-STRING FUNCTION |
DESCRIPTION |
RETURN |
|
strcpy(s1, s2) |
Copies the
contents of s2 into s1 and appends a NULL character to s1. Note: there is no boundary checking done on
the size of s1. |
Pointer to s1 |
|
strcat(s1, s2) |
Concatenates s2
onto the end of s1 and appends a NULL character to s1. Note: there is no boundary checking done on
the size of s1. |
Pointer to s1 |
|
strlen(s) |
Determines the
length of s. Note: the NULL character
is not counted as part of the length of the string. |
Length of the
characters in the string not including the NULL character. |
|
strcmp(s1, s2) |
Determines if s1
is equal to s2. The comparison is done
in lexicographic order. |
Integer value less
than 0 if s1is less than s2, equal to 0 if s1 is equal to s2, and greater
than 0 if s1 is greater than s2. |
o
C-string Input /
Output
//
A basic example of C-string I/O:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[80], s2[80];
cout << “Enter some words: ”;
cin >> s1 >> s2;
cout << “You entered ” << s1 << s2 << endl;
return 0;
}
Good output and good input (Note: the white space is stripped from the output)
Enter some words: Hello World!
You entered HelloWorld!
Good output, but bad input (Note: the input was more than the program expected. What happened to “You?”?)
Enter some words: How Are You?
You entered HowAre
//
Example that gets a whole line (getline() member function)
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s[80];
cout << “Enter some words: ”;
cin.getline(s, 80); // Note: the maximum # characters is 79 due to NULL
cout << “You entered ” << s << endl;
return 0;
}
Good output:
Enter some words: Hello World! How Are You?
You entered Hello World! How Are You?
// Other
member functions useful for C-string I/O
|
MEMBER FUNCTION |
DESCRIPTION |
|
cin.get(c) |
Gets the next
character in the input stream and puts it into the character variable, c |
|
cout.put(c) |
Takes a character
as an argument and puts the character to the screen |
|
cin.ignore(num,
‘\n’) |
Skips over input
up to the delimiter (in this case, ‘\n’).
If num is reached first, the skipping stops. |
//
Some useful Character-Manipulation Functions.
Note:
//
you must include the <cctype> library functions.
|
CHARACTER MANIPULATION FUNCTIONS |
DESCRIPTION |
|
toupper(c) |
Takes a char as an
argument and returns the upper-cased version of the argument. The char, c, is
unaffected. |
|
tolower(c) |
Takes a char as an
argument and returns the lower-cased version of the argument. The char, c, is unaffected. |
|
isupper(c) |
Takes a char as an
argument and returns Boolean true if the char is upper-cased. The char, c, is unaffected. |
|
islower(c) |
Takes a char as an
argument and returns Boolean true if the char is lower-cased. The char, c, is unaffected. |
|
isalpha(c) |
Takes a char as an
argument and returns Boolean true if the char is a letter of the
alphabet. The char, c, is unaffected. |
|
isdigit(c) |
Takes a char as an
argument and returns Boolean true if the char is a character between ‘0’ and
‘9’. The char, c, is unaffected. |
|
isalnum(c) |
Takes a char as an
argument and returns Boolean true if the char is a character that is a letter
of the alphabet or is a character that is between ‘0’ and ‘9’. The char, c, is unaffected. |
|
isspace(c) |
Takes a char as an
argument and returns Boolean true if the char is a whitespace character. The char, c, is unaffected. |
·
The Standard
Class string – Allows the programmer to treat strings as a basic
data type without needing to worry about implementation details.
o
Overloaded
operators can be used for assigning and concatenating strings.
o
Default
constructor initializes empty string. A
second constructor takes a C-string argument in the declaration.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1, s2(“Hello World. ”), s3 = “How are you?”, s4(s2);
s1 = s2 + s3;
cout << “String 1 = ” << s1 << endl;
cout
<< “String 2 = ” << s2 << endl;
cout << “String 3 = ” << s3 << endl;
cout << “String 4 = ” << s4 << endl;
return 0;
}
// The output is shown below
String 1 = Hello World. How are you?
String 2 = Hello World.
String 3 = How are you?
String 4 = Hello World.
o
The string objects
do not include the NULL character with the text of the string as is done with a
C-string variable. The string class
member functions allow you to use C-string variables, but be aware that there
are differences.
// This is legal because the memory is dynamically allocated within the object.
string s1;
s1 = “Hello World”;
// This is also legal.
char s2[80] = “Hello World”;
// This is NOT legal because s3 cannot point to anything other than the
// character array s3. You must use strcpy() function to set s3 in this example.
char s3[80];
s3 = “Hello World”;
// Note: The object s1 does not have a NULL character after the ‘d’ in world,
// but the C-string s2 does have a NULL character after the ‘d’ in world.
// More Examples:
string s4(“Have a nice day.”);
char s5[80];
s5 = s4; // NOT legal
strcpy(s5, s4); // NOT legal
strcpy(s5, s4.c_str()); // Legal
o
Input / Output
with the class string
§
The Insertion
Operator will display string objects just as any other data types.
// Example
string courseName(“This is C++ Programming.”);
cout << courseName << endl;
§
The extraction
Operator will get whitespace- delimited strings and put into string
objects. It will also ignore any leading
whitespace.
// Example
string firstName;
cout << “What is your first name? ”;
cin >> firstName;
cout
<< “Hello ” << firstName << endl;
§
To get an entire
line of input and put into a string object, use the getline() function. Notice that it is used differently for string
objects than it was used for C-strings.
// Example
string fullName;
cout << “What is your full name? ”;
getline(cin,
fullName);
cout << “Hello ” << fullName << endl;
·
Useful Member
Functions of the Standard Class string
|
MEMBER FUNCTION |
DESCRIPTION |
USAGE |
|
string s; |
Uses the default
constructor to create an empty string object, s |
Constructor |
|
string s(“test”); |
Creates string
object, s, with the “test” data. No
NULL in object. |
Constructor |
|
string s(s2) |
Creates string
object that is a copy of s2(which is also a string object). |
Constructor |
|
s.at(i) |
Returns a Read/Write
reference to the ith character in the s object. Same as s[i]. |
Element Access |
|
s.substr(a,b) |
Returns substring
of the calling object starting at a and having b length. |
Element Access |
|
s1 = s2; |
Allocates memory
for s2’s data, releases memory that was originally allocated for s1, and sets
the size of s1 to that of s2. |
Assignment/ Modifier |
|
s1 += s2; |
Concatenate s2
data to the end of s1 and set the size of s1 accordingly. |
Assignment/ Modifier |
|
s.empty() |
Returns Boolean
true if s is an empty string; otherwise it returns false. |
Assignment/ Modifier |
|
s1 + s2 |
Returns a string
that has s2 concatenated to the end of s1.
Also sets the size accordingly. |
Assignment/ Modifier |
|
s1 == s2 s1 != s2 |
Compare for
equality or inequality of s1 and s2. Returns Boolean value. |
Comparisons |
|
s1 < s2 s1 > s2 s1 <= s2 s1 >= s2 |
Lexicographical
comparisons between s1 and s2. Returns
a Boolean value. |
Comparisons |
|
s1.find(s2) |
Returns the index
of the first occurrence of s2 in s1. |
Comparisons |
|
s1.find(s2,p) |
Returns the index
of the first occurrence of s2 in s1 starting at position p. |
Comparisons |