CS-210 Sample Codes Practice
CS-210 Sample Codes Practice
##########################################################
1)
# includ <iostream>
using namespace std;
int main() {
int wage;
return 0;
###################################################################################
##########################################################
2)
/* The following code (explained later) at the top of a file enables the program to
get input and put output: (# include <iostream> etc) */
#include <iostream>
using namespace std;
int main() {
int wage;
wage = 20;
return 0;
}
###################################################################################
##########################################################
3)
In C++ There are two types of commenting, single line and multi line:
/* This is
a double line
comment, examples
below */
#include <iostream>
using namespace std;
/*
This program calculates the amount of pasta to cook, given the
number of people eating.
int main() {
int numPeople; // Number of people that will be eating
int totalOuncesPasta; // Total ounces of pasta to serve numPeople
return 0;
}
###################################################################################
##########################################################
4)
# include <iostream>
using namespace std;
int main() {
int myFirstVar; // Aligned comments yield less
int yetAnotherVar; // visual clutter
int thirdVar;
// Above blank line seperates user input statements from the rest
yetAnotherVar = myFirstVar; // Aligned = operators
thirdVar = yetAnotherVar + 1;
// Also notice the single-space on the left and right of + and =
// (except when aligning the second = with the first =)
cout << "Final value is " << thirdVar << endl; // Single-space on each side
of <<
return 0; // The above blank line seperates the return line from the rest
}
###################################################################################
##########################################################
5)
Below are some sample types of instructions that a processor might be able to
execute, where X, Y, Z, and num are each an integer.
Add X, #num, Y Adds data in memory location X to the number num, storing result
in location Y.
Sub X, #num, Y Subtracts num from data in location X, storing result in location
Y.
Mul X, #num, Y Multiplies data in location X by num, storing result in location
Y.
Div X, #num, Y Divides data in location X by num, storing result in location Y.
Jmp Z Tells the processor that the next instruction to execute is in memory
location Z.
###################################################################################
##########################################################
6) The following example is of a 'manipulator' which is a function that
overloads the insertion operator << or the extraction operator >> to adjust the
way output appears. Manipulators are defined in the iomanip and ios libraries in
namespace std.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double miles = 765.4261;
return 0;
}
###################################################################################
##########################################################
7) Table of manipulators, descriptions, and examples.
Manipulator Description
Example
cout <<
setprecision(3) << showpoint << 99.0;
###################################################################################
##########################################################
8) Example of text alignment manipulators.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Dog age in human years (dogyears.com)
cout << setw(10) << left << "Dog age" << "|";
cout << setw(12) << right << "Human age" << endl;
cout << setw(10) << left << "2 months" << "|"
cout << setw(12) << right << "14 months" << endl;
cout << setw(10) << left << "6 months" << "|";
cout << setw(12) << right << "5 years" << endl;
cout << setw(12) << left << "8 months" << "|";
cout << setw(10) << right << "9 years" << endl;
cout << setw(12) << left << "1 year" << "|";
cout << setw(12) << right << "15 years" << endl;
return 0;
}
###################################################################################
##########################################################
9) Table of Text-Alignment Manipulators
Manipulator Description
Example
setw(n) Sets the number of characters for the next output item only
// " Amy"
(does not persist, in contrast to other manipulators).
// " George"
By default, the item will be right-aligned, and filled with
spaces. cout << setw(7) << "Amy" << endl;
From <iomanip> cout
<< setw(7) << "George" << endl;
###################################################################################
##########################################################
10) Table with descriptions and example of buffer manipulators.
Manipulator Description
Example
###################################################################################
##########################################################
Compound operators
###################################################################################
##########################################################
Scientific notation is useful for representing floating-point numbers that are much
greater than or much less than 0, such as 6.02 x 1023. A floating-point literal
using scientific notation is written using an e preceding the power-of-10 exponent,
as in 6.02e23 to represent 6.02 x 1023. The e stands for exponent. Likewise, 0.001
is 1 x 10-3 and can be written as 1.0e-3. For a floating-point literal, good
practice is to make the leading digit non-zero.
###################################################################################
##########################################################
A good practice is to minimize the use of literal numbers in code. One reason is to
improve code readability. newPrice = origPrice - 5 is less clear than newPrice =
origPrice - priceDiscount. When a variable represents a literal, the variable's
value should not be changed in the code. If the programmer precedes the variable
declaration with the keyword const, then the compiler will report an error if a
later statement tries to change that variable's value. An initialized variable
whose value cannot change is called a constant variable. A common convention, or
good practice, is to name constant variables using upper case letters with words
separated by underscores, to make constant variables clearly visible in code.
###################################################################################
##########################################################
Basics
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double sideSquare;
double areaSquare = 49.0;
sideSquare = sqrt(areaSquare);
return 0;
}
###################################################################################
##########################################################
When the operands of / are integers, the operator performs integer division, which
does not generate any fraction. If at least one operand is floating-point, then
instead / does floating point division.
###################################################################################
##########################################################
Modulo (%)
The basic arithmetic operators include not just +, -, *, /, but also %. The modulo
operator (%) evaluates the remainder of the division of two integer operands. Ex:
23 % 10 is 3.
Examples:
Modulo examples
Given a random number randNum, % can generate a random number within a range:
randNum % 10
Yields 0 - 9: Possible remainders are 0, 1, ..., 8, 9. Remainder 10 is not
possible: Ex: 19 % 10 is 9, but 20 % 10 is 0.
randNum % 51
Yields 0 - 50: Note that % 50 would yield 0 - 49.
(randNum % 9) + 1
Yields 1 - 9: The % 9 yields 9 possible values 0 - 8, so the + 1 yields 1 - 9.
(randNum % 11) + 20
Yields 20 - 30: The % 11 yields 11 possible values 0 - 10, so the + 20 yields
20 - 30.
Given a number, % and / can be used to get each digit. For a 3-digit number userVal
like 927:
Given a 10-digit phone number stored as an integer, % and / can be used to get any
part, such as the prefix. For phoneNum = 1365551212 (whose prefix is 555):
###################################################################################
##########################################################
Type conversions
A type conversion is a conversion of one data type to another, such as an int to a
double. The compiler automatically performs several common conversions between int
and double types, such automatic conversions are known as implicit conversion.
* For assignments, the right side type is converted to the left side type.
Type casting
###################################################################################
##########################################################
Binary : Use a binary calculator if this ever comes up, which I doubt that it
really will...
###################################################################################
##########################################################
2.14 Characters
Basics
A variable of char type, as in char myChar;, can store a single character like the
letter m. A character literal is surrounded with single quotes, as in myChar =
'm';.
###################################################################################
##########################################################
2.15 Strings
Some variables should hold a string. A string data type isn't built into C++ like
char, int, or double, but is available in the standard library and can be used
after adding: #include <string>. A programmer can then declare a string variable
as: string firstName;.
^ I missed this the first go through, don't forget this! Would have been
frustrating to run into later.
A programmer can assign a string just as for other types. Ex: str1 = "Hello", or
str1 = str2. The string type automatically reallocates memory for str1 if the
right-side string is larger or smaller, and then copies the characters into str1.
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentenceSubject;
string sentenceVerb;
string sentenceObject = "an apple";
sentenceSubject = "boy";
sentenceVerb = "ate";
return 0;
}
Below shows the basic approach to get a string from input into variable userString.
The approach automatically skips initial whitespace, then gets characters until the
next whitespace is seen.
For such cases, the language supports getting an entire line into a string. The
function getline(cin, stringVar) gets all remaining text on the current input line,
up to the next newline character (which is removed from input but not put in
stringVar).
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName;
string lastName;
return 0;
}
###################################################################################
##########################################################
int and double are the most common numeric data types. However, several other
numeric types exist. The following table summarizes available integer numeric data
types.
The size of integer numeric data types can vary between compilers, for reasons
beyond our scope. The following table lists the sizes for numeric integer data
types used in this material along with the minimum size for those data types
defined by the language standard.
###################################################################################
##########################################################
2.18 Unsigned
#include <iostream>
using namespace std;
int main() {
unsigned long memSizeGiB;
unsigned long long memSizeBytes;
unsigned long long memSizeBits;
cout << "Memory size in bytes: " << memSizeBytes << endl;
cout << "Memory size in bits: " << memSizeBits << endl;
return 0;
}
###################################################################################
##########################################################
Some programs need to use a random number. Ex: A game program may need to roll
dice, or a website program may generate a random initial password.
The rand() function, in the C standard library, returns a random integer each time
the function is called, in the range 0 to RAND_MAX.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
cout << rand() << endl;
cout << rand() << endl;
cout << rand() << endl;
cout << "(RAND_MAX: " << RAND_MAX << ")" << endl;
return 0;
}
OUTPUT:
16807
282475249
1622650073
(RAND_MAX: 2147483647)
Each call to rand() returns a random integer between 0 and a large number RAND_MAX.
A programmer usually wants a smaller number of possible values, for which % can be
used. % (modulo) means remainder. rand() % 3 has possible remainders of 0, 1, and
2.
Specific ranges
The technique above generates random integers with N possible values ranging from 0
to N-1, like 6 values from 0 to 5. Commonly, a programmer wants a specific range
that starts with some value x that isn't 0, like 10 to 15, or -20 to 20. The
programmer should first determine the number of values in the range, generate a
random integer with that number of possible values, and then add x to adjust the
range to start with x.
#include <iostream>
#include <cstdlib>
using namespace std;
// Switch a student
// from a random seat on the left (cols 1 to 15)
// to a random seat on the right (cols 16 to 30)
// Seat rows are 1 to 20
int main() {
int rowNumL;
int colNumL;
int rowNumR;
int colNumR;
return 0;
}
Pseudo-random (Seeds)
The integers generated by rand() are known as pseudo-random. "Pseudo" means "not
actually, but having the appearance of". The integers are pseudo-random because
each time a program runs, calls to rand() yield the same sequence of values.
Earlier in this section, a program called rand() three times and output 16807,
282475249, 1622650073. Every time the program is run, those same three integers
will be printed. Such reproducibility is important for testing some programs.
(Players of classic arcade games like Pac-man may notice that the seemingly-random
actions of objects actually follow the same pattern every time the game is played,
allowing players to master the game by repeating the same winning actions).
Internally, the rand() function has an equation to compute the next "random"
integer from the previous one, (invisibly) keeping track of the previous one. For
the first call to rand(), no previous random integer exists, so the function uses a
built-in integer known as the seed. By default, the seed is 1. A programmer can
change the seed using the function srand(), as in srand(2) or srand(99).
If the seed is different for each program run, the program will get a unique
sequence. One way to get a different seed for each program run is to use the
current time as the seed. The function time() returns the number of seconds since
Jan 1, 1970.
Note that the seeding should only be done once in a program, before the first call
to rand().
###################################################################################
##########################################################
###################################################################################
##########################################################
A program commonly needs to determine if two items are equal. Ex: If a hotel gives
a discount for guests on their 50th wedding anniversary, a program to calculate the
discount can check if a variable numYears is equal to the value 50. A programmer
can use an if statement to check if two values are equal.
The example below uses ==. The equality operator (==) evaluates to true if the left
and right sides are equal. Ex: If numYears is 50, then numYears == 50 evaluates to
true. Note the equality operator is ==, not =.
#include <iostream>
using namespace std;
int main() {
int hotelRate;
int numYears;
hotelRate = 150;
if (numYears == 50) {
cout << "Congratulations on 50 years "
<< "of marriage!" << endl;
hotelRate = hotelRate / 2;
}
return 0;
}
Whereas the equality operator checks whether two values are equal, the inequality
operator (!=) evaluates to true if the left and right sides are not equal, or
different.
###################################################################################
##########################################################
If-else statement
#include <iostream>
using namespace std;
int main() {
int userNum;
int divRemainder;
divRemainder = userNum % 2;
if (divRemainder == 0) {
cout << userNum << " is even." << endl;
}
else {
cout << userNum << " is odd." << endl;
}
return 0;
}
if (expression1) {
// Statements that execute when expression1 is true
// (first branch)
}
else if (expression2) {
// Statements that execute when expression1 is false and expression2 is true
// (second branch)
}
else {
// Statements that execute when expression1 is false and expression2 is false
// (third branch)
}
###################################################################################
##########################################################
Logical operators
Special symbols are used to represent the AND, OR, and NOT logical operators.
Logical operators are commonly used in expressions of if-else statements.
###################################################################################
##########################################################
The order in which operators are evaluated in an expression are known as precedence
rules. Arithmetic, logical, and relational operators are evaluated in the order
shown below.
Operator/Convention Description
Explanation
###################################################################################
##########################################################
3.11 Switch statements
Switch statement
switch (userVal) {
case 1:
numItems = 5;
break;
case 3:
numItems = 12;
break;
case 4:
numItems = 99;
break;
default:
numItems = 55;
break;
}
Omitting the break statement for a case will cause the statements within the next
case to be executed. Such "falling through" to the next case can be useful when
multiple cases, such as cases 0, 1, and 2, should execute the same statements.
The following extends the previous program for dog ages less than 1 year old. If
the dog's age is 0, the program asks for the dog's age in months. Within the
switch (dogAgeMonths) statement, "falling through" is used to execute the same
display statement for several values of dogAgeMonths. For example, if dogAgeMonths
is 0, 1 or 2, the same statement executes.
A common error occurs when the programmer forgets to include a break statement at
the end of a case's statements.
switch (expression) {
case constantExpr1:
// Statements
break;
case constantExpr2:
// Statements
break;
...
switch (userChar) {
case 'A':
encodedVal = 1;
break;
case 'B':
encodedVal = 2;
break;
case 'C':
case 'D':
encodedVal = 4;
break;
case 'E':
encodedVal = 5;
case 'F':
encodedVal = 6;
break;
default:
encodedVal = -1;
break;
}
###################################################################################
##########################################################
3.12 Boolean data type
Boolean refers to a quantity that has only two possible values, true or false. C++
has the built-in data type bool for representing Boolean quantities.
A Boolean variable may be set using true or false keywords. Ex: isMale = true;
assigns isMale with the Boolean value true. A Boolean variable may also be set to
the result of a logical expression. Ex: isOverweight = (userBmi >= 25); assigns
isOverweight with the result of the expression userBmi >= 25.
int main() {
int waitTime;
int partySize;
char day;
bool isLargeParty;
bool isWeekend;
return 0;
}
if (isReallyHot) {
// Use A/C and evaporative cooler
acOn = true;
evapCoolerOn = true;
}
else if (isHot && isHumid) {
// Use A/C
acOn = true;
evapCoolerOn = false;
}
else if (isHot && !isHumid) {
// Use evaporative cooler
acOn = false;
evapCoolerOn = true;
}
else {
acOn = false;
evapCoolerOn = false;
}
###################################################################################
##########################################################
#include <iostream>
#include <string>
using namespace std;
int main() {
string userWord;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string userWord ="Caterpillar";
int replaceIndex;
userWord.at(replaceIndex) = '*';
return 0;
}
sample in/out:
Enter an index (0-10): 0
Updated string: *aterpillar
...
...
A common task is to append (add to the end) a string to an existing string. The
function s1.append(s2) appends string s2 to string s1. Ex: If s1 is "Hey",
s1.append("!!!") makes s1 "Hey!!!".
The example program below might be part of a "caption contest" for a website where
a user enters a string below an image. The program automatically adds a period if
the user did not include any punctuation at the caption's end.
int main() {
string userCaption;
char lastChar;
int lastIndex;
lastIndex = userCaption.size() - 1;
lastChar = userCaption.at(lastIndex);
return 0;
}
sample in/out:
Enter a caption: Hello world
New: Hello world.
...
...
...
...
The .at(index) function generates an exception if the index is out of range for the
string's size. An exception is a detected runtime error that commonly prints an
error message and terminates the program.
C++ also supports C-style access of a string using brackets [] rather than .at(),
as in: someString[0]. However, such C-style access does not provide such error
checking. Good practice is to use .at() rather than brackets for accessing a
string's characters, due to .at()'s error checking.
###################################################################################
##########################################################
Including the cctype library via #include <cctype> provides access to several
functions for working with characters. ctype stands for character type. The first c
indicates the library is originally from the C language.
int main() {
char let0;
char let1;
sample in/out:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string userPassword;
getline(cin, userPassword);
return 0;
}
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string userPassword;
getline(cin, userPassword);
return 0;
}
###################################################################################
##########################################################
Read in a 3-character string from input into variable passCode. Declare a boolean
variable isValid and set isValid to true if passCode does not contain any
alphabetic characters. Otherwise, set isValid to false.
Passcode accepted
Note: Use getline(cin, passCode) to read the entire line from input into passCode.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string passCode;
return 0;
}
Ex: If the input is qD, then containsLowercase is assigned with true, so the output
is:
Password is valid
Ex: If the input is !2, then containsLowercase is assigned with false, so the
output is:
Note: Use getline(cin, userPassword) to read the entire line from input into
userPassword.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string userPassword;
bool containsLowercase;
if (containsLowercase) {
cout << "Password is valid" << endl;
}
else {
cout << "Password is not valid" << endl;
}
return 0;
}
THESE ARE TRICKY AF FOR SOME REASON I FIND THE SYNTAX MIND BOGGLING... DEFINATELY
PRACTICE THESE...
###################################################################################
##########################################################
#include <iostream>
#include <string>
using namespace std;
int main() {
string emailText;
int atSymbolIndex;
string emailUsername;
atSymbolIndex = emailText.find('@');
if (atSymbolIndex == string::npos) {
cout << "Address is missing @" << endl;
}
else {
emailUsername = emailText.substr(0, atSymbolIndex);
cout << "Username: " << emailUsername << endl;
}
return 0;
}
###################################################################################
##########################################################
The string library provides numerous useful functions, including functions for
finding a character or string within a string, or getting a substring of a string.
userText.find("me") // Returns 5
userText.substr(13, 4)
// Returns
".com"
userText.substr(userText.size() - 4, 4)
// Last 4:
".com"
Combining / Replacing
userText.size(); // Returns 6
// userText
is "Goodbye"
userText.insert(4, "---");
// Now
"Good---bye"
str1 + str2 Returns a new string that is a copy of str1 with str2 appended.
// userText is "A B"
myString =
userText + " C D";
If one of str1, str2 is a string, the other may be a
// myString is "A B C D"
character (or character array).
myString = myString + '!';
// myString
now "A B C D!"
myString =
myString + userText;
// myString
now "A B C D!A B"
#include <iostream>
#include <string>
using namespace std;
int main() {
string userName;
string greetingText;
int itemIndex;
itemIndex = 0;
...
str1 is "Main" and str2 is " Street" (note the leading space).
str2.push_back('.');
str1.replace(1, 2, "our");
###################################################################################
##########################################################
If-else statements with the form shown below are so common that the language
supports the shorthand notation shown.
Form 1: Shorthand:
All three operands are expressions. If the condition evaluates to true, then
exprWhenTrue is evaluated. If the condition evaluates to false, then exprWhenFalse
is evaluated. The conditional expression evaluates to whichever of those two
expressions was evaluated. For example, if x is 2, then the conditional expression
(x == 2) ? 5 : 9 * x evaluates to 5.
A conditional expression has three operands and thus the "?" and ":" together are
sometimes referred to as a ternary operator.
###################################################################################
##########################################################
Floating-point numbers should not be compared using ==. Ex: Avoid float1 == float2.
Reason: Some floating-point numbers cannot be exactly represented in the limited
available memory bits like 64 bits. Floating-point numbers expected to be equal may
be close but not exactly equal.
Floating-point numbers should be compared for "close enough" rather than exact
equality. Ex: If (x - y) < 0.0001, x and y are deemed equal. Because the difference
may be negative, the absolute value is used: fabs(x - y) < 0.0001. fabs() is a
function in the math library. The difference threshold indicating that floating-
point numbers are equal is often called the epsilon. Epsilon's value depends on the
program's expected values, but 0.0001 is common.
numMeters = 0.7;
numMeters = numMeters - 0.4;
numMeters = numMeters - 0.3;
// numMeters expected to be 0,
// but is actually -0.0000000000000000555112
if (numMeters == 0.0) {
// Equals 0.
}
else {
// Does not equal 0.
}
Bug
if (fabs(numMeters - 0.0) < 0.001) {
// Equals 0.
}
else {
// Does not equal 0.
}
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double bodyTemp;
return 0;
}
###################################################################################
##########################################################
A logical operator evaluates operands from left to right. Short circuit evaluation
skips evaluating later operands if the result of the logical operator can already
be determined. The logical AND operator short circuits to false if the first
operand evaluates to false, and skips evaluating the second operand. The logical OR
operator short circuits to true if the first operand is true, and skips evaluating
the second operand.
###################################################################################
##########################################################
3.22 Loops (general)
9 - 7 = 2
2:7
7-2 = 5
2:5
5-2 = 3
2:3
Basics
A loop commonly must iterate a specific number of times, such as 10 times. Though
achievable with a while loop, that situation is so common that a special kind of
loop exists. A for loop is a loop with three parts at the top: a loop variable
initialization, a loop expression, and a loop variable update. A for loop describes
iterating a specific number of times more naturally than a while loop.
The statement i = i + 1 is so common that the language supports the shorthand ++i,
with ++ known as the increment operator. (Likewise, -- is the decrement operator,
--i means i = i - 1). As such, a standard way to loop N times is shown below.
int i;
...
for (i = 0; i < N; ++i) {
...
}
Note: Actually two increment operators exist: ++i (pre-increment) and i++ (post-
increment). ++i increments before evaluating to a value, while i++ increments
after. Ex: If i is 5, outputting ++i outputs 6, while outputting i++ outputs 5 (and
then i becomes 6). This material primarily uses ++i for simplicity and safety,
although many programmers use i++, especially in for loops.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string inputWord;
int numLetters;
unsigned int i;
numLetters = 0;
for (i = 0; i < inputWord.size(); ++i) {
if (isalpha(inputWord.at(i))) {
numLetters += 1;
}
}
return 0;
}
// U.S.A. is 6 long
userText.replace(usaIndex, 6, "USA");
}
return 0;
}
###################################################################################
##########################################################
I AM STILL JANKY AT ITERATING THROUGH STRINGS FOR SOME REASON WITH
REPLACE...CHALLENGES....
#include <iostream>
#include <string>
using namespace std;
int main() {
string passPhrase;
unsigned int i;
getline(cin, passPhrase);
return 0;
}
"qwerty" is a string commonly found in weak passwords. Use a while loop to count
the number of occurrences of "qwerty" in secretStr, and replace each occurrence of
"qwerty" in secretStr with an empty string("").
string.find(item) returns the index of the first occurrence of item in string. If
no occurrence is found, then the function returns string::npos.
str.replace(indx, n, "") replaces the n characters starting at index indx of str
with an empty string.
#include <iostream>
#include <string>
using namespace std;
int main() {
string secretStr;
int count;
int indx;
count = 0;
indx = 0;
if (secretStr.find("qwerty") != string::npos) {
count += 1;
}
return 0;
}
###################################################################################
##########################################################
Nested loops have various uses. One use is to generate all combinations of some
items. For example, the following program generates all two-letter .com Internet
domain names.
#include <iostream>
using namespace std;
letter1 = 'a';
while (letter1 <= 'z') {
letter2 = 'a';
while (letter2 <= 'z') {
cout << letter1 << letter2 << ".com" << endl;
++letter2;
}
++letter1;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int userNum;
int i;
int j;
return 0;
}
Given numRows and numColumns, print a list of all seats in a theater. Rows are
numbered, columns lettered, as in 1A or 3E. Print a space after each seat,
including after the last. Ex: numRows = 2 and numColumns = 3 prints:
1A 1B 1C 2A 2B 2C
#include <iostream>
using namespace std;
int main() {
int numRows;
int numColumns;
int currentRow;
int currentColumn;
char currentColumnLetter;
return 0;
}
###################################################################################
##########################################################
3.32 Enumerations
###################################################################################
##########################################################
4.2 Vectors
The statement above declares a vector with the specified number of elements, each
element of the specified data type. The type of each vector element is specified
within the angle brackets (<>). The number of vector elements is specified within
parentheses following the vector name. Ex: vector<int> gameScores(4); declares a
vector gameScores with 4 integer elements.
Terminology note: { } are braces. < > are angle brackets, or chevrons. In a vector
access, the number in .at() parentheses is called the index of the corresponding
element. The first vector element is at index 0.
If you have studied arrays, then know that a vector was added to C++ as a safer and
more powerful form of arrays, discussed elsewhere.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> itemCounts(3);
itemCounts.at(0) = 122;
itemCounts.at(1) = 119;
itemCounts.at(2) = 117;
return 0;
}
A vector's index must be an unsigned integer type. The vector index cannot be a
floating-point type, even if the value is 0.0, 1.0, etc.
The program below allows a user to print the age of the Nth oldest known person to
have ever lived. The program quickly accesses the Nth oldest person's age using
oldestPeople.at(nthPerson - 1). Note that the index is nthPerson - 1 rather than
just nthPerson because a vector's indices start at 0, so the 1st age is at index 0,
the 2nd at index 1, etc.
Figure 4.2.1: Vector's ith element can be directly accessed using .at(i
- 1): Oldest people program.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> oldestPeople(5);
int nthPerson; // User input, Nth oldest person
return 0;
}
Enter N (1..5): 1
The #1 oldest person lived 122 years.
...
Enter N (1..5): 4
The #4 oldest person lived 117 years.
...
Enter N (1..5): 9
...
Enter N (1..5): 0
...
Enter N (1..5): 5
The #5 oldest person lived 116 years.
###################################################################################
##########################################################
4.2.4: Vector declaration and accesses.
A: vector<int> myVals(10);
A: x = myVals.at(8);
3) Given myVals has 10 elements, assign the last element in myVals with the value
555.
A: myVals.at(9) = 555;
4) Assign myVals element at the index held in currIndex with the value 777.
A: myVals.at(currIndex) = 777;
5) Assign tempVal with the myVals element at the index one after the value held in
variable i.
A key advantage of vectors becomes evident when used in conjunction with loops. The
program below uses a loop to allow a user to enter 8 integer values, storing those
values in a vector, and then printing those 8 values.
A vector's size() function returns the number of vector elements. Ex: In the
program below, userVals.size() is 8 because the vector was declared with 8
elements.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NUM_VALS = 8; // Number of elements in vector
vector<int> userVals(NUM_VALS); // User values
unsigned int i; // Loop index
cout << "Enter " << NUM_VALS << " integer values..." << endl;
for (i = 0; i < userVals.size(); ++i) {
cout << "Value: ";
cin >> userVals.at(i);
}
return 0;
}
Vector initialization
A vector's elements are automatically initialized to 0s during the vector
declaration.
A programmer may initialize each vector element with different values by specifying
the initial values in braces {} separated by commas. Ex: vector<int> carSales = {5,
7, 11}; creates a vector of three integer elements initialized with values 5, 7,
and 11. Such vector declaration and initialization does not require specifying the
vector size, because the vector's size is automatically set to the number of
elements within the braces. For a larger vector, initialization may be done by
first declaring the vector, and then using a loop to assign vector elements.
Feedback?
Note that index variable i is initialized to 0, and the loop expression is i <
myVector.size() rather than i <= myVector.size(). If myVector.size() were 5, the
loop's iterations would set i to 0, 1, 2, 3, and 4, for a total of 5 iterations.
The benefit of the loop structure is that each vector element is accessed as
myVector.at(i) rather than the more complex myVector.at(i - 1).
int main() {
const int NUM_ELEMENTS = 8; // Number of elements in vector
vector<int> userVals(NUM_ELEMENTS); // User values
unsigned int i; // Loop index
int sumVal; // For computing sum
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < userVals.size(); ++i) {
cout << "Value: ";
cin >> userVals.at(i);
cout << endl;
}
// Determine sum
sumVal = 0;
for (i = 0; i < userVals.size(); ++i) {
sumVal = sumVal + userVals.at(i);
}
cout << "Sum: " << sumVal << endl;
return 0;
}
The program below determines the maximum value in a user-entered list. If the user
enters numbers 7, -9, 55, 44, 20, -400, 0, 2, then the program will output "max:
55". The program uses the variable maxVal to store the largest value seen thus far
as the program iterates through the vector. During each iteration, if the vector's
current element value is larger than the max seen thus far, the program assigns
maxVal with the current vector element.
Before entering the loop, maxVal must be initialized to some value because maxVal
will be compared with each vector element's value. A logical error would be to
initialize maxVal to 0, because 0 is not in fact the largest value seen so far, and
would result in incorrect output (of 0) if the user entered all negative numbers.
Instead, the program peeks at a vector element (in this case the first element,
though any element could be used) and initializes maxVal with that element's value.
###################################################################################
##########################################################
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NUM_VALS = 8; // Number of elements in vector
vector<int> userVals(NUM_VALS); // User values
unsigned int i; // Loop index
int maxVal; // Computed max
cout << "Enter " << NUM_VALS << " integer values..." << endl;
for (i = 0; i < userVals.size(); ++i) {
cout << "Value: ";
cin >> userVals.at(i);
}
return 0;
}
###################################################################################
##########################################################
4.5 Vector resize
Commonly, the size of a list of items is not known during a program's compile time.
Thus, a vector's size need not be specified in the vector's declaration. Instead, a
vector's size can be set or changed while a program executes using resize(N). Ex:
highScore.resize(10) resizes the highScores vector to have 10 elements.
resize() can be called multiple times. If the new size is larger, resize() adds
elements at the end. If smaller, resize() deletes elements from the end. If
userScores has size 3 (elements 0, 1, 2), userScores.resize(2); would delete
element 2, leaving elements 0 and 1. A subsequent access to userScores.at(2) would
result in an error.
###################################################################################
##########################################################
Sometimes a program must swap values among two variables. Swapping two variables x
and y means to assign y's value to x, and x's value to y. If x is 33 and y is 55,
then after swapping x is 55 and y is 33.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
vector<int> revVctr(NUM_ELEMENTS); // User values
unsigned int i; // Loop index
int tmpValue; // Placeholder
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < revVctr.size(); ++i) {
cout << "Value: ";
cin >> revVctr.at(i);
}
// Reverse
for (i = 0; i < (revVctr.size() / 2); ++i) {
tmpValue = revVctr.at(i); // These 3 statements swap
revVctr.at(i) = revVctr.at(revVctr.size() - 1 - i);
revVctr.at(revVctr.size() - 1 - i) = tmpValue;
}
// Print values
cout << endl << "New values: ";
for (i = 0; i < revVctr.size(); ++i) {
cout << " " << revVctr.at(i);
}
cout << endl;
return 0;
}
New values: 80 70 60 50 40 30 20 10
We should ensure the program works if the number of elements is odd rather than
even. Suppose the vector has 5 elements (0-4) with values 10 20 30 40 50.
revVctr.size() / 2 would be 5 / 2 = 2, meaning the loop expression would be i < 2.
The iteration when i is 0 would swap elements 0 and 4 (5-1-0), yielding 50 20 30 40
10. The iteration for i=1 would swap elements 1 and 3, yielding 50 40 30 20 10. The
loop would then not execute again because i is 2. So the results are correct for an
odd number of elements, because the middle element will just not move.
The mistakes made above are each very common when dealing with loops and vectors,
especially for beginning programmers. An incorrect (in this case out-of-range)
index, an incorrect swap, and an incorrect loop expression. The lesson is that
loops and vectors require attention to detail, greatly aided by manually executing
the loop to determine what is happening on each iteration. Ideally, a programmer
will take more care when writing the original program, but the above mistakes are
quite common.
###################################################################################
##########################################################
4.8 Arrays vs. vectors
Vectors are safer because the access v.at(i) is checked during execution to ensure
the index is within the vector's valid range. An array access a[i] involves no such
check. Such checking is important; trying to access an array with an out-of-range
index is a very common error, and one of the hardest errors to debug.
int userWeights[3];
int userAge;
userAge = 44;
userWeights[0] = 122;
userWeights[1] = 119;
userWeights[2] = 117;
userWeights[3] = 199; // (Problematic)
// Print userAge
As shown above, assigning with an out-of-range index can mysteriously change some
other variable's value. Debugging such an error can be a nightmare.
Vectors have more advantages, like resizing during runtime, easy insertion of items
at the front or rear, determining vector size, etc., discussed later. Arrays have
minor benefits that don't really outweigh drawbacks. Like choosing to not wear
seatbelts, choosing to not use vectors may be quite risky.
C++ allows vectors to be accessed using brackets [], but brackets involve no range
checking, so a good practice is to use .at() to access vector elements.
###################################################################################
##########################################################
4.9 Two-dimensional arrays
An array can be declared with two dimensions. int myArray[R][C] represents a table
of int variables with R rows and C columns, so R*C elements total. For example, int
myArray[2][3] creates a table with 2 rows and 3 columns, for 6 int variables total.
Example accesses are myArray[0][0] = 33; or num = myArray[1][2].
###################################################################################
##########################################################
Figure 4.9.1: Using a two-dimensional array: A driving distance
between cities example.
#include <iostream>
using namespace std;
int main() {
int cityA; // Starting city
int cityB; // Destination city
int drivingDistances[3][3]; // Driving distances
if ((cityA >= 0) && (cityA <= 2) && (cityB >= 0) && (cityB <= 2)) {
cout << "Distance: " << drivingDistances[cityA][cityB];
cout << " miles." << endl;
}
return 0;
}
###################################################################################
##########################################################
Construct 4.9.1: Initializing a two-dimensional array
during declaration.
// Initializing a 2D array
int numVals[2][3] = { {22, 44, 66}, {97, 98, 99} };
4.10 C++ example: Annual salary tax rate calculation with vectors
zyDE 4.10.1: Various tax rates.
Vectors are useful to process tabular information. Income taxes are based on annual
salary, usually with a tiered approach. Below is an example of a simple tax table:
The below program uses a vector salaryBase to hold the cutoffs for each salary
level and a parallel vector taxBase that has the corresponding tax rate.
Run the program and enter annual salaries of 40000 and 60000, then enter 0.
Modify the program to use two parallel vectors named annualSalaries and taxesToPay,
each with 10 elements. Vectors annualSalaries holds up to 10 annual salaries
entered; vector taxesToPay holds up to 10 corresponding amounts of taxes to pay for
those annual salaries. Print the total annual salaries and taxes to pay after all
input has been processed.
Run the program again with the same annual salary numbers as above.
The following program calculates the tax rate and tax to pay based on annual
income.
###################################################################################
##########################################################
zyDE 4.10.2: Various tax rates (solution).
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int MAX_ELEMENTS = 10;
int annualSalary;
double taxRate;
int taxToPay;
int totalSalaries;
int totalTaxes;
int numSalaries;
bool keepLooking;
unsigned int i;
int j;
vector<int> salaryBase(5);
vector<double> taxBase(5);
vector<int> annualSalaries(MAX_ELEMENTS);
vector<int> taxesToPay(MAX_ELEMENTS);
salaryBase.at(0) = 0;
salaryBase.at(1) = 20000;
salaryBase.at(2) = 50000;
salaryBase.at(3) = 100000;
salaryBase.at(4) = 99999999;
taxBase.at(0) = 0.0;
taxBase.at(1) = 0.10;
taxBase.at(2) = 0.20;
taxBase.at(3) = 0.30;
taxBase.at(4) = 0.40;
numSalaries = 0;
// Sum the annual salaries and taxes to pay and print the totals
totalSalaries = 0;
totalTaxes = 0;
return 0;
}
###################################################################################
##########################################################
4.11.1: LAB: Sort a vector
4.11 LAB: Sort a vector
5 10 4 39 12 2
the output is:
39,12,10,4,2,
For coding simplicity, follow every output value by a comma, including the last
one.
Hint: Sorting a vector can be done in many ways. You are welcome to look up and use
any existing algorithm. Some believe the simplest to code is bubble sort:
https://en.wikipedia.org/wiki/Bubble_sort. But you are welcome to try others:
https://en.wikipedia.org/wiki/Sorting_algorithm.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
/* Type your code here */
// number we take from user to determine size of array
int n;
// read the val from the user and pass it to variable n
cin >> n;
// create an integer array of the size n taken from the user
vector<int> myVec(n);
^ Aight so I cheated and used AI to help because wtf I don't even think we have
learned how to define functions unless I somehow stumbled through that? What an
insane complexity creep in one problem worth a fraction of points... I hate this
class sometimes.
###################################################################################
##########################################################
5.1 User-defined function basics
Functions (general)
A program may perform the same operation repeatedly, causing a large and confusing
program due to redundancy. Program redundancy can be reduced by creating a grouping
of predefined statements for repeatedly used operations, known as a function. Even
without redundancy, functions can prevent a main program from becoming large and
confusing.
Pizza Funk
#include <iostream>
using namespace std;
double CalcPizzaArea() {
double pizzaDiameter;
double pizzaRadius;
double pizzaArea;
double piVal = 3.14159265;
pizzaDiameter = 12.0;
pizzaRadius = pizzaDiameter / 2.0;
pizzaArea = piVal * pizzaRadius * pizzaRadius;
return pizzaArea;
}
int main() {
cout << "12 inch pizza is " << CalcPizzaArea();
cout << " inches squared." << endl;
return 0;
}
Squares in a Funk
#include <iostream>
using namespace std;
int main() {
int numSquared;
numSquared = ComputeSquare(7);
cout << "7 squared is " << numSquared << endl;
return 0;
}
Other return types are allowed, such as char, double, etc. A function can only
return one item, not two or more. A return type of void indicates that a function
does not return any value.
Questions:
A: True!
2) The following is a valid function definition for a function that returns two
items:
int, int GetItems() { ... }
A: False: A function can only return one item, not two or more.
True: A void return type means the function returns no value. Ex: A function that
outputs data may have no need to return a value. The function typically has no
return statement (but may have: return; with no expression).
###################################################################################
##########################################################
Parameters
#include <iostream>
using namespace std;
int main() {
cout << "12.0 inch pizza is "<< CalcPizzaArea(12.0)
<< " square inches." << endl;
cout << "16.0 inch pizza is "<< CalcPizzaArea(16.0)
<< " square inches." << endl;
return 0;
}
Questions:
2) Write a statement that calls a function named CalcCalories, passing the value 3
as an argument.
A: CalcCalories(3);
A: 4321
Multiple or no parameters
A function definition with no parameters must still have the parentheses, as in:
int DoSomething() {...}. The vall must include parenthesis, with no argument, as
in: DoSomething().
###################################################################################
##########################################################
Figure 5.1.1: Function with multiple parameters.
#include <iostream>
using namespace std;
int main() {
cout << "12.0 x 0.3 inch pizza is " << CalcPizzaVolume(12.0, 0.3);
cout << " inches cubed." << endl;
cout << "12.0 x 0.8 inch pizza is " << CalcPizzaVolume(12.0, 0.8);
cout << " inches cubed." << endl;
cout << "16.0 x 0.8 inch pizza is " << CalcPizzaVolume(16.0, 0.8);
cout << " inches cubed." << endl;
return 0;
}
###################################################################################
##########################################################
A function's statements may call other functions. In the example below, the
PizzaCalories() function calls the CalcCircleArea() function. (Note that main()
itself is the first function called when a program executes, and calls other
functions.)
return circleArea;
}
return totalCalories;
}
int main() {
cout << "12 inch pizza has " << PizzaCalories(12.0) << " calories." << endl;
cout << "14 inch pizza has " << PizzaCalories(14.0) << " calories." << endl;
return 0;
}
Complete the function definition to return the hours given minutes. Output for
sample program when the user inputs 210.0:
3.5
#include <iostream>
using namespace std;
int main() {
double minutes;
return 0;
}
###################################################################################
##########################################################
Pass by reference
Pass by reference parameters should be used sparingly. For the case of two return
values, commonly a programmer should instead create two functions. For example,
defining two separate functions int StepsToFeet(int baseSteps) and int
StepsToCalories(int baseSteps) is better than a single function void
StepsToFeetAndCalories(int baseSteps, int& baseFeet, int& totCalories) . The
separate functions support modular development, and enables use of the functions in
an expression as in if (StepsToFeet(mySteps) < 100).
Using multiple pass by reference parameters makes sense when the output values are
intertwined, such as computing monetary change, whose function might be void
ComputeChange(int totCents, int& numQuarters, int& numDimes, int& numNickels, int&
numPennies), or converting from polar to Cartesian coordinates, whose function
might be void PolarToCartesian(int radialPol, int anglePol, int& xCar, int& yCar).
Complete the monetary change program. Use the fewest coins (i.e., using maximum
larger coins first).
#include <iostream>
using namespace std;
int main() {
int userCents;
int numQuarters;
int numDimes;
int numNickels;
int numPennies;
// FIXME add variables for dimes, nickels, pennies
return 0;
}
Reference variables
In the example below, usrValRef is a reference that refers to usrValInt. The user-
entered number is assigned to the variable usrValInt. Because usrValRef refers to
usrValInt, printing usrValInt or usrValRef will print the number.
#include <iostream>
using namespace std;
int main() {
int usrValInt;
int& usrValRef = usrValInt; // Refers to usrValInt
usrValInt = 99;
cout << endl << "We assigned usrValInt with 99." << endl;
cout << "usrValInt is now: " << usrValInt << "." << endl;
cout << "usrValRef is now: " << usrValRef << "." << endl;
cout << "Note that usrValRef refers to usrValInt, so it changed too." << endl;
return 0;
}
###################################################################################
##########################################################
CHALLENGE ACTIVITY
5.10.1: Function pass by reference: Transforming
coordinates.
Define a function CoordTransform() that transforms the function's first two input
parameters xVal and yVal into two output parameters xValNew and yValNew. The
function returns void. The transformation is new = (old + 1) * 2. Ex: If xVal = 3
and yVal = 4, then xValNew is 8 and yValNew is 10.
#include <iostream>
using namespace std;
int usrValInt;
int& usrValRef = usrValInt;
/* Your solution goes here */
void CoordTransform(int xVal, int yVal, int& xValNew, int& yValNew) {
xValNew = (xVal + 1) * 2;
yValNew = (yVal + 1) * 2;
}
int main() {
int xValNew;
int yValNew;
int xValUser;
int yValUser;
return 0;
}
###################################################################################
##########################################################
#include <iostream>
using namespace std;
int main() {
int usrCups;
int usrTablespoons;
int totalTablespoons;
cout << usrCups << " cups and " << usrTablespoons << " tablespoons" << endl;
return 0;
}
###################################################################################
##########################################################
Define a function GetWeight() that takes one integer parameter passed by reference
as totalOunces and two integer parameters as pounds and ounces. If both pounds and
ounces are non-negative, the function computes totalOunces and returns true.
Otherwise, the function returns false without updating totalOunces.
Notes:
#include <iostream>
using namespace std;
int main() {
int totalOunces;
int pounds;
int ounces;
bool valid;
totalOunces = 0;
cin >> pounds;
cin >> ounces;
if (valid) {
cout << "Total ounces: " << totalOunces << endl;
}
else {
cout << "Invalid. Total ounces: " << totalOunces << endl;
}
return 0;
}
###################################################################################
##########################################################
#include <iostream>
#include <string>
using namespace std;
int main() {
string userStr; // Input string from user
return 0;
}
...
The following illustrates. The first function modifies the vector so it defines a
normal pass by reference. The second function does not modify the vector but for
efficiency uses constant pass by reference.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NUM_VALUES = 8; // Vector size
vector<int> userValues(NUM_VALUES); // User values
int i; // Loop index
return 0;
}
Enter 8 values...
Value: 10
Value: 20
Value: 30
Value: 40
Value: 50
Value: 60
Value: 70
Value: 80
New values: 80 70 60 50 40 30 20 10
A reader might wonder why all input parameters are not defined as constant pass by
reference parameters: Why make local copies at all? The reason is efficiency. For
parameters involving just a few memory locations, making a local copy enables the
compiler to generate more efficient code, in part because the compiler can place
those copies inside a tiny-but-fast memory inside the processor called a register
file—further details are beyond our scope.
In summary:
Define a function's output or input/output parameters as pass by reference.
But create output parameters sparingly, striving to use return values instead.
Define input parameters as pass by value.
Except for large items (perhaps 10 or more elements); use constant pass by
reference for those.
PARTICIPATION ACTIVITY
5.11.1: Constants and pass by reference.
How should a function's vector parameter ages be defined for the following
situations?
1) ages will always be small (fewer than 10 elements) and the function will not
modify the vector.
Constant prevents the function from modifying ages. Since ages is small, pass by
reference is not used; instead, a copy of ages is made.
2) ages will always be small, and the function will modify the vector.
Pass by reference makes ages modifiable, but constant prevents ages from being
modified.
3) ages may be very large, and the function will modify the vector.
Pass by reference makes ages modifiable, but constant prevents ages from being
modified.
4) ages may be very large, and the function will not modify the vector.
Constant prevents the function from modifying ages. Since ages is large, pass by
reference is used to pass the original vector, instead of creating a copy.
PARTICIPATION ACTIVITY
Define a function's vector parameter ages for the following situations. Assume ages
is a vector of integers. Example: ages will always be small (fewer than 10
elements) and the function will not modify the vector: const vector<int> ages.
1) ages will always be small, and the function will modify the vector.
Because the vector will be modified, the parameter must be pass by reference, and
of course cannot be constant. The size is not relevant; to be modified, the
parameter must be pass by reference.
2) ages may be very large, and the function will modify the vector
Pass by reference but not constant. Because the function modifies the vector, the
size is irrelevant.
3) ages may be very large, and the function will not modify the vector.
Pass by reference (achieved using &) and constant (achieved using const).
Complete the function to replace any period by an exclamation point. Ex: "Hello.
I'm Miley. Nice to meet you." becomes:
"Hello! I'm Miley! Nice to meet you!"
#include <iostream>
#include <string>
using namespace std;
int main() {
string testStr;
getline(cin, testStr);
MakeSentenceExcited(testStr);
cout << testStr;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> sortVector(4);
unsigned int i;
int userNum;
SwapVectorEnds(sortVector);
return 0;
}
Complete the function GetLastIndex() that has one string parameter and one
character parameter. The function returns the index of the last character in the
string that is not equal to the character parameter. If no such character is found,
the function returns -1.
Ex: If the input is tnmmb m, then the output is:
#include <iostream>
using namespace std;
}
else {
return 0;
}
}
}
int main() {
string inString;
char x;
int result;
return 0;
}