0% found this document useful (0 votes)
111 views134 pages

(UPE Tutoring) CS 31 Midterm 1 Review (Spring '18)

The document provides an overview and examples of key concepts for CS 31 Midterm 1 including libraries and namespaces, basic data types, input/output, C++ strings, if/else statements, switches, and loops. It includes code snippets and explanations of functions like string size(), substr(), and the + operator for appending to strings. The document also provides links to sign up for a review session and access the slides.

Uploaded by

Blimey Blame
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views134 pages

(UPE Tutoring) CS 31 Midterm 1 Review (Spring '18)

The document provides an overview and examples of key concepts for CS 31 Midterm 1 including libraries and namespaces, basic data types, input/output, C++ strings, if/else statements, switches, and loops. It includes code snippets and explanations of functions like string size(), substr(), and the + operator for appending to strings. The document also provides links to sign up for a review session and access the slides.

Uploaded by

Blimey Blame
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 134

UPE Tutoring:

CS 31 Midterm 1 Review
Sign-in https://goo.gl/forms/6qZYWQkI1du22pUx1
Slides https://goo.gl/f5SYLZ

UPSILON PI EPSILON
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Table of Contents
● Scoping
● Libraries & Namespaces
● Functions (probably not on midterm)
● Types & Variables
● Practice:
● Basic Input/Output
○ String to Int
● C++ Strings
○ isPalindrome
● If/Else
○ Get “Switchy”
● Switches
● Good Luck!
● Loops
○ Practice: Pile of Money

UPSILON PI EPSILON
2
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Libraries
● #include allows us to use a library
● #include <iostream> allows us to use things like:
○ cin
○ cout
○ endl
● Note: iostream stands for input/output stream

UPSILON PI EPSILON
3
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Namespaces
● using namespace std;
● A namespace is a collection of classes and functions
● If we don't call using namespace ns_name, we will have to specify the namespace of the
function we want to call.
● e.g. std::cout, std::string, std::isdigit

UPSILON PI EPSILON
4
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Namespaces (cont.)
#include <iostream> #include <iostream>
using namespace std;
int main() {
int age; int main() {
std::cin >> age; int age;
std::cout << age; cin >> age;
std::cout << std::endl; cout << age;
} cout << endl;
}

UPSILON PI EPSILON
5
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Basic data types
● int, double, char
○ Declare variables to store values in memory
○ int x; // Creates a variable x of type int
○ char y; // Creates a variable y of type char
● Can initialize with value at declaration:
○ int a = 5;
○ double z = 53.24324;

UPSILON PI EPSILON
6
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Modifying variables
● The type of the variable must be specified only once, at the time of declaration

int x = 5;
x = x + 5;
x -= 6; // equivalent to x = x - 6;

double z;
z = 53.234;
z *= 5; // equivalent to z = z * 5;

UPSILON PI EPSILON
7
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Modifying variables (cont.)
● Integer division truncates after the decimal point
● The % (modulus) operator returns the remainder of integer division

int x = 5;
int integerQuotient = x / 3; // integerQuotient equals 1
int remainder = x % 3; // remainder equals 2
x %= 4; // same as x = x % 4, x now equals 1

UPSILON PI EPSILON
8
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Modifying variables (cont.)
● Double division
○ If at least one of the operands is a double, floating point division occurs.
○ If both values are integers, integer division occurs instead.

int x = 5;
double unexpectedQuotient = x / 2; // equals 2.0
double expectedQuotient = x / 2.0; // equals 2.5

UPSILON PI EPSILON
9
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Input/Output
#include <iostream>
using namespace std;
int main() {
int age;
cout << "How old are you? " << endl;
cin >> age;
cout << "You are " << age <<
" years old" << endl;
}

UPSILON PI EPSILON
10
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Input/Output
#include <iostream>
using namespace std;
int main() {
int age;
cout << "How old are you? " << endl;
cin >> age;
cout << "You are " << age <<
" years old" << endl;
}

age
UPSILON PI EPSILON
11
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How old are you?
Input/Output
#include <iostream>
using namespace std;
int main() {
int age;
cout << "How old are you? " << endl;
cin >> age;
cout << "You are " << age <<
" years old" << endl;
}

age
UPSILON PI EPSILON
12
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How old are you? 20
Input/Output
#include <iostream>
using namespace std;
int main() {
int age;
cout << "How old are you? " << endl;
cin >> age;
cout << "You are " << age <<
" years old" << endl;
}

20

age
UPSILON PI EPSILON
13
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How old are you? 20
Input/Output > You are 20 years old

#include <iostream>
using namespace std;
int main() {
int age;
cout << "How old are you? " << endl;
cin >> age;
cout << "You are " << age <<
" years old" << endl;
}

20

age
UPSILON PI EPSILON
14
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Strings
● Used to store blocks of text
● Strings can be initialized from literals
○ string x = “hello”;
● Individual characters can be accessed with the [ ] operator.
○ char c = x[0]; // c == ‘h’

UPSILON PI EPSILON
15
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
String Operations
string x = "hello there";

● The size() method returns the number of characters in a string.


○ int length = x.size(); // length equals 11
● The substr(startIndex, length) method returns a substring including startIndex of
length length.
○ string sub = x.substr(3, 2); // sub equals "lo"

UPSILON PI EPSILON
16
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
String Operations
// The + operator is overloaded:
// It appends to the end of strings.

int main() {
string x = "hello there";
x += ", my name is Mark";
cout << x << endl;
}

hello there

x
UPSILON PI EPSILON
17
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
String Operations
// The + operator is overloaded:
// It appends to the end of strings.

int main() {
string x = "hello there";
x += ", my name is Mark";
cout << x << endl;
}

hello there, my name is Mark

x
UPSILON PI EPSILON
18
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> hello there, my name is Mark
String Operations
// The + operator is overloaded:
// It appends to the end of strings.

int main() {
string x = "hello there";
x += ", my name is Mark";
cout << x << endl;
}

hello there, my name is Mark

x
UPSILON PI EPSILON
19
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
String Input
// getline(...) consumes characters from
// the input until it encounters a '\n'.

int main() {
string x;
getline(cin, x);
cout << x << endl;
}

UPSILON PI EPSILON
20
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
String Input
// getline(...) consumes characters from > Why hello there!
// the input until it encounters a '\n'.

int main() {
string x;
getline(cin, x);
cout << x << endl;
}

UPSILON PI EPSILON
21
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
String Input
// getline(...) consumes characters from > Why hello there!
// the input until it encounters a '\n'. > Why hello there!

int main() {
string x;
getline(cin, x);
cout << x << endl;
}

UPSILON PI EPSILON
22
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Ignoring Characters
● Undesirable characters are often left in the input buffer after using cin.
● cin.ignore(int numChars, char delim) can be used to “flush” out these undesired
characters. It flushes up to the nearest delim or numChar characters, whichever comes
first.
● cin.ignore(...) becomes necessary if after reading a number, the next thing you want
to read is a string using getline(...).

UPSILON PI EPSILON
23
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Ignoring Characters
● Undesirable characters are often left in the input buffer after using cin.
● cin.ignore(int numChars, char delim) can be used to “flush” out these undesired
characters. It flushes up to the nearest delim or numChar characters, whichever comes
first.
● cin.ignore(...) becomes necessary if after reading a number, the next thing you want
to read is a string using getline(...).

● Common question: does getline consume '\n'?

UPSILON PI EPSILON
24
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Ignoring Characters
● Undesirable characters are often left in the input buffer after using cin.
● cin.ignore(int numChars, char delim) can be used to “flush” out these undesired
characters. It flushes up to the nearest delim or numChar characters, whichever comes
first.
● cin.ignore(...) becomes necessary if after reading a number, the next thing you want
to read is a string using getline(...).

● Common question: does getline consume '\n'?


If a newline is found, it is extracted and discarded (i.e. it is not stored and the next
input operation will begin after it).

UPSILON PI EPSILON
25
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How many Big Macs would you like?
cin.ignore example
int main() {
cout << "How many Big Macs would you " <<
"like? ";
int bigMacs;
cin >> bigMacs;
cin.ignore(10000, '\n'); // Important!

cout << "What else would you like " <<


"with your order?";
string sides;
getline(cin, sides);
}

Input
UPSILON PI EPSILON
26
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How many Big Macs would you like?
cin.ignore example
int main() {
cout << "How many Big Macs would you " <<
"like? ";
int bigMacs;
cin >> bigMacs;
cin.ignore(10000, '\n'); // Important!

cout << "What else would you like " <<


"with your order?";
string sides;
getline(cin, sides);
}

bigMacs Input
UPSILON PI EPSILON
27
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How many Big Macs would you like? 1000
cin.ignore example
int main() {
cout << "How many Big Macs would you " <<
"like? ";
int bigMacs;
cin >> bigMacs;
cin.ignore(10000, '\n'); // Important!

cout << "What else would you like " <<


"with your order?";
string sides;
getline(cin, sides);
}

1000 \n

bigMacs Input
UPSILON PI EPSILON
28
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How many Big Macs would you like? 1000
cin.ignore example
int main() {
cout << "How many Big Macs would you " <<
"like? ";
int bigMacs;
cin >> bigMacs;
cin.ignore(10000, '\n'); // Important!

cout << "What else would you like " <<


"with your order?";
string sides;
getline(cin, sides);
}

1000

bigMacs Input
UPSILON PI EPSILON
29
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How many Big Macs would you like? 1000
cin.ignore example > What else would you like with your
order?
int main() {
cout << "How many Big Macs would you " <<
"like? ";
int bigMacs;
cin >> bigMacs;
cin.ignore(10000, '\n'); // Important!

cout << "What else would you like " <<


"with your order?";
string sides;
getline(cin, sides);
}

1000

bigMacs Input
UPSILON PI EPSILON
30
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How many Big Macs would you like? 1000
cin.ignore example > What else would you like with your
order?
int main() {
cout << "How many Big Macs would you " <<
"like? ";
int bigMacs;
cin >> bigMacs;
cin.ignore(10000, '\n'); // Important!

cout << "What else would you like " <<


"with your order?";
string sides;
getline(cin, sides);
}

1000

bigMacs sides Input


UPSILON PI EPSILON
31
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> How many Big Macs would you like? 1000
cin.ignore example > What else would you like with your
order? Fries
int main() {
cout << "How many Big Macs would you " <<
"like? ";
int bigMacs;
cin >> bigMacs;
cin.ignore(10000, '\n'); // Important!

cout << "What else would you like " <<


"with your order?";
string sides;
getline(cin, sides);
}

1000 Fries

bigMacs sides Input


UPSILON PI EPSILON
32
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
cin.ignore(...) example
● What will be stored in the string “a” in this example?
● Assume that input is newline terminated.

int x; string a;
cout << "Enter an integer" << endl;
cin >> x; // Assume the user enters “7”
cout << "Enter a string" << endl;
getline(cin, a); // Assume user enters “500”

UPSILON PI EPSILON
33
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
cctype
● Useful shortcut methods for characters
● #include<cctype> gives you…
○ isalpha('M') // true, since 'M' is a letter
○ isupper('M') // true, since 'M' is an uppercase letter
○ islower('r') // true, since 'r' is a lowercase letter
○ isdigit('5') // true, since '5' is a digit character
○ islower('M') // false, since 'M' is not a lowercase letter
○ isalpha(' ') // false, since ' ' is not a letter
○ isalpha('5') // false, since '5' is not a letter

UPSILON PI EPSILON
34
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
If statements
● if statements only run code if the condition is true
● Note: any non-zero expression is considered true

int age;
cin >> age;
if (age < 13) {
cout << "You are not yet a teenager!" << endl;
}

UPSILON PI EPSILON
35
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
If statements
● Without curly braces, only next statement is attached to the control statement.
● So, if you want multiple statements to be executed, use curly braces.
● Note: this also applies to else and else-if statements

if (cond1) {
statement1;
statement2;
}

UPSILON PI EPSILON
36
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
If statements (cont.)
int main() { int main() {
int x = 3; int x = 5;
if (x == 5) if (x == 5) {
cout << "x is 5" << endl; cout << "x is 5" << endl;
cout << "In if" << endl; // Incorrectly cout << "In if" << endl;
// called! }
} }

UPSILON PI EPSILON
37
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Else statements
● Performed when all if and else if conditions fail

int number;
cin >> number;
if (number % 2 == 0)
cout << "You gave an even number" << endl;
else
cout << "You gave an odd number" << endl;

UPSILON PI EPSILON
38
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Else-if statements
● Allows us to check for more than the if condition and its complement

if (cond1)
statement1;
else if (cond2)
statement2;
else if (cond3)
statement3;
else
statement4;

UPSILON PI EPSILON
39
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Comparison pitfalls
● Equals-equals (==) vs. Equals (=)
● These operators are very different!

(x == y) // Returns true if x and y are equal

(x = y) // Assigns the value of y to x and returns the value


// ASSIGNED to x.

UPSILON PI EPSILON
40
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Conditional confusion?
● Does this output anything?

int age = 17;


if (age) {
cout << "You are not 0 years old!" << endl;
}

UPSILON PI EPSILON
41
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Conditional confusion?
● What does this output?

int age = 0;
if (age) {
cout << "You are not 0 years old!" << endl;
} else {
cout << “You are 0 years old!” << endl;
}

UPSILON PI EPSILON
42
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Switches
● Arguably a more compact alternative to long if/else if/else sequences
● The value tested must be an integral type or convertible to one
○ e.g. int, char, short, long, etc.
○ string is not a permitted type
● A break statement must be used to leave the switch. Otherwise execution will fall
through to the next case.

UPSILON PI EPSILON
43
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Switches (cont.)
Common question 1: is a break statement required
string value; int number;
for the default case?
cin >> number;
switch (number) {
case 0: // Fall-through to Case 2.
case 2:
value = "Good";
break; // Remember to break!
case 3:
value = "Bad";
break;
default:
value = "Ugly";
break;
}
UPSILON PI EPSILON
44
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Switches (cont.)
Common question 1: is a break statement required
string value; int number;
for the default case?
cin >> number;
switch (number) {
case 0: // Fall-through to Case 2.
No, if the default case is at the end. However, we
case 2: recommend that you put one anyways. This allows
value = "Good"; the default case to appear in a different order, and
break; // Remember to break! not necessarily at the end of the switch statement.
case 3:
value = "Bad";
break;
default:
value = "Ugly";
break;
}
UPSILON PI EPSILON
45
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Switches (cont.)
Common question 1: is a break statement required
string value; int number; for the default case?
cin >> number;
switch (number) {
No if the default case is at the end. However, we
case 0: // Fall-through to Case 2.
case 2: recommend that you put one anyways. This allows
value = "Good"; the default case to appear in a different order, and
break; // Remember to break! not necessarily at the end of the switch statement.
case 3:
value = "Bad"; Common question 2: do I need a default statement?
break;
default:
value = "Ugly";
break;
}
UPSILON PI EPSILON
46
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Switches (cont.)
Common question 1: is a break statement required
string value; int number; for the default case?
cin >> number;
switch (number) {
No if the default case is at the end. However, we
case 0: // Fall-through to Case 2.
case 2: recommend that you put one anyways. This allows
value = "Good"; the default case to appear in a different order, and
break; // Remember to break! not necessarily at the end of the switch statement.
case 3:
value = "Bad"; Common question 2: do I need a default statement?
break;
default:
No, but it is good to have to catch unexpected
value = "Ugly";
cases. You should leave a //comment if you don’t
break;
}
have a default to explain why!

UPSILON PI EPSILON
47
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
While loops
● while loops run code until the condition is false

int count;
cin >> count;
while (count >= 0) {
cout << "Countdown: " << count << endl;
count--;
}

UPSILON PI EPSILON
48
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
While loops
int main() {
int x = 0;
while (x < 2) {
cout << x << endl;
x++;
}
cout << "Done!" << endl;
}

x
UPSILON PI EPSILON
49
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> 0
While loops
int main() {
int x = 0;
while (x < 2) {
cout << x << endl;
x++;
}
cout << "Done!" << endl;
}

x
UPSILON PI EPSILON
50
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> 0
While loops
int main() {
int x = 0;
while (x < 2) {
cout << x << endl;
x++;
}
cout << "Done!" << endl;
}

x
UPSILON PI EPSILON
51
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> 0
While loops
int main() {
int x = 0;
while (x < 2) {
cout << x << endl;
x++;
}
cout << "Done!" << endl;
}

x
UPSILON PI EPSILON
52
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> 0
While loops > 1

int main() {
int x = 0;
while (x < 2) {
cout << x << endl;
x++;
}
cout << "Done!" << endl;
}

x
UPSILON PI EPSILON
53
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> 0
While loops > 1

int main() {
int x = 0;
while (x < 2) {
cout << x << endl;
x++;
}
cout << "Done!" << endl;
}

x
UPSILON PI EPSILON
54
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> 0
While loops > 1

int main() {
int x = 0;
while (x < 2) {
cout << x << endl;
x++;
}
cout << "Done!" << endl;
}

x
UPSILON PI EPSILON
55
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> 0
While loops > 1
> Done!
int main() {
int x = 0;
while (x < 2) {
cout << x << endl;
x++;
}
cout << "Done!" << endl;
}

x
UPSILON PI EPSILON
56
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Do-while loops
● Same as while loops, except the first iteration always runs.

statement1;
do {
statement2;
} while (cond1); // Don't forget the semicolon!

statement3;

UPSILON PI EPSILON
57
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
For loops
● Declaration is run once before anything else
● Condition is evaluated before the code block is executed
● Action is run after the code block is executed

for (declaration; condition; action) {


statement1;
statement2;
}

Note: all of the three sections of the for loop are optional; all that is required is the semicolon. If condition
is empty, it defaults to always true. Example: for(int i = 0;;i++) { //infinite loop }

UPSILON PI EPSILON
58
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
For loops
int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

UPSILON PI EPSILON
59
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
For loops
int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

i
UPSILON PI EPSILON
60
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> i is now equal to: 0
For loops
int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

i
UPSILON PI EPSILON
61
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> i is now equal to: 0
For loops
int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

i
UPSILON PI EPSILON
62
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> i is now equal to: 0
For loops
int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

i
UPSILON PI EPSILON
63
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> i is now equal to: 0
For loops > i is now equal to: 1

int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

i
UPSILON PI EPSILON
64
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> i is now equal to: 0
For loops > i is now equal to: 1

int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

i
UPSILON PI EPSILON
65
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> i is now equal to: 0
For loops > i is now equal to: 1

int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

i
UPSILON PI EPSILON
66
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> i is now equal to: 0
For loops > i is now equal to: 1
> Done!
int main() {
for (int i = 0; i < 2; i++) {
cout << "i is now equal to: " << i <<
endl;
}

// Note that i is now out of scope.


cout << "Done!" << endl;
}

UPSILON PI EPSILON
67
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Nested loops
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
cout << (i * j) << "\t";
}
cout << endl;
}

UPSILON PI EPSILON
68
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Quick Question - Breaking the Outer Loop
● What happens when you break inside nested loops?

UPSILON PI EPSILON
69
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Quick Question - Breaking the Outer Loop
● What happens when you break inside nested loops?
○ Only the loop that contains the break statement is broken out of.

UPSILON PI EPSILON
70
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Quick Question - Breaking the Outer Loop
● What happens when you break inside nested loops?
○ Only the loop that contains the break statement is broken out of.
● Solution: use a boolean variable (a flag) in your loop’s statements and change the
boolean from true to false when you want to break out of a nested loop.

bool keepLoopingI = true;


for (int i = 1; i <= 100; i++) {
for (int j = 1; j <= 200; j++) {
if (i+j > 250) keepLoopingI = false; What does this print?
cout << i << “,” << j << endl;
}
if (!keepLoopingI) break;
}

UPSILON PI EPSILON
71
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Practice Question: Pile of Money
Print a pile of money n stacks high, leaning up on the right against your mansion’s wall.

Example for n=4:


$|
$$|
$$$|
$$$$|

(Contributed by Matthew Wong)

UPSILON PI EPSILON
72
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Solution: Pile of Money
int n = 5; // Or any positive integer value

// Loop through all n rows


for (int i = 1; i <= n; i++) {
// print the spaces preceding the dollar signs
for (int spaces = 0; spaces < n - i; spaces++)
cout << " ";

// print the i dollar signs for the row


for (int money = 0; money < i; money++)
cout << "$";

// print the wall and move to the next line


cout << "|" << endl;
}

UPSILON PI EPSILON
73
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping
● Variables only exist within the curly brackets or the implied curly brackets that they were
written in.

if (cond1) {
statement1;
}

UPSILON PI EPSILON
74
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping (cont.)
if (cond1) {
int x = 5;
cout << x << endl; // No error
}

cout << x << endl; // Error!! x doesn’t exist


// outside the if statement

UPSILON PI EPSILON
75
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping (cont.)
int x = 1;
if (cond1) {
x = 5;
cout << x << endl; // No error
}

cout << x << endl; // No error here either!

UPSILON PI EPSILON
76
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping (cont.)
string s1 = “bonjour”;
for (int i = 0; i < s1.size(); i++) {
char lastChar = s1[i];
}

// Both i and lastChar don't exist here!


cout << i << " " << lastChar << endl; // Error!

UPSILON PI EPSILON
77
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping (cont.)
string s1 = “bonjour”;
int i; char lastChar;
for (i = 0; i < s1.size(); i++) {
lastChar = s1[i];
}

// Now both i and lastChar exist here


cout << i << " " << lastChar << endl;

UPSILON PI EPSILON
78
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping: Switch Statements

int main() {
int n;
cin >> n;
switch (n) {
case 1:
int x = 10;
cout << "You entered 1! 1 times 10 is " << x << endl;
break;
default:
int x = 5;
cout << "You didn't enter 1" << endl;
}
}

UPSILON PI EPSILON
79
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping: Switch Statements
Warning: the cases of a switch statement share the same scope!

int main() {
int n;
cin >> n;
switch (n) {
case 1:
int x = 10;
cout << "You entered 1! 1 times 10 is " << x << endl;
break;
default:
int x = 5; // This is an error! Compiler says “error: redefinition of 'x'”
cout << "You didn't enter 1" << endl;
}
}

UPSILON PI EPSILON
80
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping: Switch Statements
Warning: the cases of a switch statement share the same scope!

int main() {
int n;
cin >> n;
switch (n) {
case 1:
int x = 10;
cout << "You entered 1! 1 times 10 is " << x << endl;
break;
default:
// Does x exist here? It's within the switch’s curly braces, but "int x = 10" was never executed?!
cout << "You didn't enter 1" << endl;
}
}

UPSILON PI EPSILON
81
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping: Switch Statements
Warning: the cases of a switch statement share the same scope!

int main() {
int n;
cin >> n;
switch (n) {
case 1:
int x = 10;
cout << "You entered 1! 1 times 10 is " << x << endl;
break;
default:
// So, this is also an error! Compiler says "note: jump bypasses variable initialization"
cout << "You didn't enter 1" << endl;
}
}

UPSILON PI EPSILON
82
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Scoping: Switch Statements
Warning: the cases of a switch statement share the same scope!

int main() {
int n;
cin >> n;
switch (n) {
case 1: {
int x = 10; // Now x is only known to the scope of this case
cout << "You entered 1! 1 times 10 is " << x << endl;
break;
}
default:
cout << "You didn't enter 1" << endl;
}
}

UPSILON PI EPSILON
83
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: The Box Model

functionName
Input1

Input2 Output

Input3

UPSILON PI EPSILON
84
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Simple Example
#include <iostream>
using namespace std;

int hypotenuse(int side1, int side2) {


/* Function body */
/* We don’t need to know how the function is implemented */
...
}

int main() {
int x = hypotenuse(3,4);
}

UPSILON PI EPSILON
85
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Mathematical Example
● f(x, y, z) = x - y - z;
functionName
● f(10, 5, 4) = 10 - 5 - 4 = 1
● f(3, 5, 4) = 3 - 5 - 4 = -6 Input1

● Symbolically, x, y, and z are Input2 Output

input1, input2, and input3


Input3

UPSILON PI EPSILON
86
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
> -3
Math Example (cont.)
Suppose we define f(x, y, z) = x - y - z.

int main() {
int b = 5;
int a = 4;
int c = 6;
cout << f(c,b,a) << endl;
}

5 4 6
Then for some variables a, b, c, we
have f(c, b, a) = c - b - a = 6 - 5 - 4 = -3. b a c
UPSILON PI EPSILON
87
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Mathematical Example (cont.)
#include <iostream>
using namespace std;
int functionName(int num1, int num2, int num3) {
return num1 - num2 - num3;
}

● f(x, y, z) becomes functionName(num1, num2, num3)


● functionName(10, 5, 4) = 10 - 5 - 4 = 1;
● functionName(3, 5, 4) = 3 - 5 - 4 = -6;

UPSILON PI EPSILON
88
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Scoping
● Variables declared outside the function do not exist inside the function unless they are
global variables

const int foo = 6;


string functionName(int a, int b) {
cout << x << endl; // x does not exist here, so this is an ERROR.
int y = 5 + foo; // This is okay because foo is global.
return y + a + b;
}

UPSILON PI EPSILON
89
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Scoping (cont.)
Variables declared inside the function do not exist outside the function

int main() {
int x = 4;
cout << functionName(4,5) << endl;
cout << y << endl; // y does not exist here, so this is an error!
}

UPSILON PI EPSILON
90
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Nested Loops Example
Problem: Find the first character in string1 that exists in string2, or return the null byte if no
such character is found.

Examples:
● string1 = “hello”, string2 = “there”, result = ‘h’
● string1 = “aabc”, string2 = “xyzab”, result = ‘a’
● string1 = “aabc”, string2 = “xyzzb”, result = ‘b’
● string1 = “abcd”, string2 = “wxyz”, result = ‘\0’

UPSILON PI EPSILON
91
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: The Box Model
char firstChar(string string1, string string2);

firstChar

Input1: string1

Output: a char
Input2: string2

UPSILON PI EPSILON
92
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Nested Loops Solution
char firstChar(string1, string2) {
for (int i = 0; i < string1.size(); i++)
for (int j = 0; j < string2.size(); j++)
if (string1[i] == string2[j])
return string1[i];
return ‘\0’;
}

UPSILON PI EPSILON
93
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Calling the firstChar Function
int main() {
cout << firstChar(“hello”, “there”) << endl;
cout << firstChar(“aabc”, “xyzab”) << endl;
cout << firstChar(“aabc”, “xyzzb”) << endl;
}

UPSILON PI EPSILON
94
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++)
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j])
return string1[i];
return '\0';
}

int main() {
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
95
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++)
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j])
return string1[i];
return '\0';
}

int main() {
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
96
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough "hello" "there"

string1 string2
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++)
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j])
return string1[i];
return '\0';
}

int main() {
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
97
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough "hello" "there"

string1 string2
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++) 'h'
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j]) string1[i]
return string1[i];
return '\0';
} 0

int main() { i
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
98
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough "hello" "there"

string1 string2
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++) 'h' 't'
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j]) string1[i] string2[j]
return string1[i];
return '\0';
} 0 0

int main() { i j
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
99
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough "hello" "there"

string1 string2
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++) 'h' 't'
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j]) string1[i] string2[j]
return string1[i];
return '\0';
} 0 0

int main() { i j
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
100
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough "hello" "there"

string1 string2
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++) 'h' 'h'
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j]) string1[i] string2[j]
return string1[i];
return '\0';
} 0 1

int main() { i j
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
101
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough "hello" "there"

string1 string2
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++) 'h' 'h'
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j]) string1[i] string2[j]
return string1[i];
return '\0';
} 0 1

int main() { i j
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
102
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough "hello" "there"

string1 string2
char firstChar(string string1,
string string2) {
for (int i=0; i < string1.size(); i++) 'h' 'h'
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j]) string1[i] string2[j]
return string1[i];
return '\0';
} 0 1

int main() { i j
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
103
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough
char firstChar(string string1, > h
string string2) {
for (int i=0; i < string1.size(); i++)
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j])
return string1[i];
return '\0';
}

int main() {
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
104
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Walkthrough
char firstChar(string string1, > h
string string2) {
for (int i=0; i < string1.size(); i++)
for (int j=0; j < string2.size(); j++)
if (string1[i] == string2[j])
return string1[i];
return '\0';
}

int main() {
cout << firstChar("hello", "there");
}

UPSILON PI EPSILON
105
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Parameters
● The types, modifiers, order, and number of parameters are all important in a function
declaration
○ types: string, int, bool, etc.
○ modifiers: &, const, *, etc.
○ number: how many parameters are passed to a particular function?

● Function call must match the pattern of the declaration

UPSILON PI EPSILON
106
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(string s1, string s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
string x = isEqual(s1,s2, position);
}

UPSILON PI EPSILON
107
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(string s1, string s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
string x = isEqual(s1,s2, position);
}

No. The return type is boolean.

UPSILON PI EPSILON
108
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(string s1, string s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
bool x = isEqual(s1,s2);
}

UPSILON PI EPSILON
109
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(string s1, string s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
bool x = isEqual(s1,s2);
}

No. The number of arguments doesn’t match.

UPSILON PI EPSILON
110
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(string s1, string s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
bool x = isEqual(position, s1, s2);
}

UPSILON PI EPSILON
111
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(string s1, string s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
bool x = isEqual(position, s1, s2);
}

No. The order of arguments doesn’t match.

UPSILON PI EPSILON
112
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(string s1, string s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
bool x = isEqual(s1, s2, position);
}

UPSILON PI EPSILON
113
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(string s1, string s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
bool x = isEqual(s1, s2, position);
}

Yes.

UPSILON PI EPSILON
114
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(const string& s1, const string& s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
bool x = isEqual(s1, s2, position);
}

UPSILON PI EPSILON
115
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Will this compile?
// Assume this function is defined later.
bool isEqual(const string& s1, const string& s2, int position);

int main() {
string s1 = "hello";
string s2 = "there";
int position = 1;
bool x = isEqual(s1, s2, position);
}

Yes. Notice the argument passing syntax is identical for pass by reference.

UPSILON PI EPSILON
116
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Pass by Value
● By default, all parameters in C++ are pass by value.
● Every pass by value parameter is copied into the function

bool containsLowerCase(string s);

int main() {
string s1 = “really long string”;
containsLowerCase(s1); // a copy of s1 is made and
} // passed to containsLowerCase

UPSILON PI EPSILON
117
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Pass by Reference
● A reference to a variable is passed to the function instead of a copy of the variable
● Syntax: add an & between parameter type and name
○ int& x, bool& b, string& s
● If these variables are changed inside the function, then they will also be changed
outside.

UPSILON PI EPSILON
118
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: swap
● Does this function properly swap the two variables passed to it?

void swap(int x, int y) {


int temp = x;
x = y;
y = temp;
}

UPSILON PI EPSILON
119
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: swap
● Does this function properly swap the two variables passed to it?

void swap(int x, int y) {


int temp = x;
x = y;
y = temp;
}

No, it only swaps local copies! We need to use pass by reference.

UPSILON PI EPSILON
120
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: swap
void swap (int& x, int& y);

swap
Input1: integer x

Output: nothing???
Input2: integer y

UPSILON PI EPSILON
121
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: swap #2
● Does this function properly swap the two variables passed to it?

void swap(int& x, int& y) {


int temp = x;
x = y;
y = temp;
}

UPSILON PI EPSILON
122
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: swap #2
● Does this function properly swap the two variables passed to it?

void swap(int& x, int& y) {


int temp = x;
x = y;
y = temp;
}

Yes, because we are using the & modifier on the parameters to pass by reference.

UPSILON PI EPSILON
123
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Const Variables
● A parameter with the const modifier cannot be modified within the function. For
example, we cannot change the value of num from within the body of the function
isPrime.

bool isPrime(const int& num) {


// Cannot change value of num here.
...
}

UPSILON PI EPSILON
124
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Const Variables
● Why are they useful?
○ Gives assurance the the caller of a function that the argument they pass in won’t be
modified
○ Makes convoluted functions easier to understand if we know a certain variable
can’t be modified

● These are usually passed by reference. (It's a little weird to use it with pass by value.)

UPSILON PI EPSILON
125
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Passing by Constant Reference
● The purpose of passing by reference is to save memory or allow modifications by the
function.
● What if we want to avoid copying but don’t want to allow functions to modify the
variables we pass in?

UPSILON PI EPSILON
126
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Functions: Passing by Constant Reference
● If we pass by const reference we can:
○ avoid the cost of copying
○ prevent our variables from being modified by the function
● Essentially a free performance gain
● You’ll run into const reference often in CS32

UPSILON PI EPSILON
127
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Practice Question: String to Int
Convert a variable of type string into the integer represented by that string.
Example, convert:
string number = “125” into
int numberAsInt // holding the value 125 as an integer
Hints:
// string name = “Daniel”;
// name[0] is ‘D’
// name.size() is 6
// ‘8’ - ‘0’ (the character eight minus the character zero) is 8 (the integer eight)

(Contributed by Katie Luangkote)

UPSILON PI EPSILON
128
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Solution: String to Int
string number = “125”; // or let the user cin their own string
int result = 0;
int multiplier = 1;
for (int i = number.size() - 1; i >= 0; i--) {
result += (number[i] - '0') * multiplier;
multiplier *= 10;
}
int numberAsInt = result;

// “125” becomes 5 + 2*10 + 1*100 = 125


// Any other way to do this?

UPSILON PI EPSILON
129
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Practice Question: isPalindrome
Write a function is_palindrome that takes a
string as an argument and returns true if the
string is a palindrome and false if it is not. A
palindrome is a string that is read backwards the
same way as it is forwards. For example
"racecar" backwards is "racecar".

UPSILON PI EPSILON
130
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Solution: isPalindrome
Start by checking that the first and the last letters bool is_palindrome(string s) {
in the string are equal, then move inward until we int n = s.size();
for (int i = 0; i < n / 2; i++) {
reach the middle of the string. Note: This only
int j = (n - 1) - i;
requires n / 2 iterations of the for-loop. Also, if (s[i] != s[j]) return false;
this code works even when n is odd. Trace }
through an example by hand to see why! return true;
}

UPSILON PI EPSILON
131
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Practice Question: Get “Switchy”
int main() {
string morty; ...
int rick = 5; morty += morty;
rick = (rick + 2 * 5) / 10; morty[0] = ‘w’;
switch (rick) {
case 1: for (int i = 0; i < 2; i++)
morty = “lubba”; morty += “dub”;
break;
case 3: cout << morty << endl;
morty = “aw geez”; }
break;
default:
morty = “oh man”;
break; What is the output of this code?
}
...

UPSILON PI EPSILON
132
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Solution: Get “Switchy”
int main() {
string morty; ...
int rick = 5; morty += morty; morty = “lubbalubba”
rick = (rick + 2 * 5) / 10; rick = 1 morty[0] = ‘w’; morty = “wubbalubba”
switch (rick) {
case 1: for (int i = 0; i < 2; i++)
morty = “lubba”; morty = “lubba” morty += “dub”; morty = “wubbalubbadubdub”
break;
case 3: cout << morty << endl;
morty = “aw geez”; }
break;
default:
morty = “oh man”;
break; Output: wubbalubbadubdub
} Translation: I am in great pain please help me
...

UPSILON PI EPSILON
133
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ
Good luck!
Sign-in https://goo.gl/3tYKJY
Slides https://goo.gl/BkV8Ds
Practice https://github.com/uclaupe-tutoring/practice-problems/wiki

Questions? Need more help?


● Come up and ask us! We'll try our best.
● UPE offers daily computer science tutoring:
○ Location: ACM/UPE Clubhouse (Boelter 2763)
○ Schedule: https://upe.seas.ucla.edu/tutoring/
● You can also post on the Facebook event page.

UPSILON PI EPSILON
134
CS 31 Midterm 1 Review (Spring ‘18) https://goo.gl/f5SYLZ

You might also like