Lecture2
Lecture2
reading:
Programming Abstractions in C++, Chapters 2-3
This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
Based on slides created by Keith Schwarz, Julie Zelenski, Marty Stepp, Ashley Taylor, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, and others.
Plan for Today
• C++ Functions
– Syntax
– Prototypes
– Pass by reference
• Announcements
• Strings
– Common functions and patterns
– C strings vs. C++ strings
2
Plan for Today
• C++ Functions
– Syntax
– Prototypes
– Pass by reference
• Announcements
• Strings
– Common functions and patterns
– C strings vs. C++ strings
3
Defining a function (2.3)
• A C++ function is like a Java method.
return type parameters (arguments)
parameters (arguments)
• Calling a function:
4
Defining a function
#include <iostream>
#include "console.h"
using namespace std;
int main() {
for (int i = 99; i > 0; i--) {
bottlesOfPop(i);
}
return 0;
} 5
Lots of Pop
99 bottles of pop on the wall.
99 bottles of pop.
Take one down, pass it around, 98 bottles of pop on the wall.
98 bottles of pop on the wall.
98 bottles of pop.
Take one down, pass it around, 97 bottles of pop on the wall.
97 bottles of pop on the wall.
97 bottles of pop.
Take one down, pass it around, 96 bottles of pop on the wall.
...
3 bottles of pop on the wall.
3 bottles of pop.
Take one down, pass it around, 2 bottles of pop on the wall.
2 bottles of pop on the wall.
2 bottles of pop.
Take one down, pass it around, 1 bottles of pop on the wall.
1 bottles of pop on the wall.
1 bottles of pop.
Take one down, pass it around, 0 bottles of pop on the wall.
6
Defining a function
// Returns the area of a circle with the given radius.
double circleArea(int r) {
return 3.14 * r * r;
}
int main() {
double a1 = circleArea(1); // call the function
double a2 = circleArea(3); // call it again
cout << "The area is " << a1 << "!!" << endl;
return 0;
}
7
Defining a function
// Returns the area of a circle with the given radius.
double circleArea(int r) {
return 3.14 * r * r;
}
int main() {
double a1 = circleArea(1); // call the function
double a2 = circleArea(3); // call it again
double a3 = circleArea(3.1); // truncates!
cout << "The area is " << a1 << "!!" << endl;
return 0;
}
8
Overloading
// Returns the area of a circle with the given radius.
double circleArea(int r) {
return 3.14 * r * r;
}
int main() {
double a1 = circleArea(1); // call the function
double a2 = circleArea(3); // call it again
double a3 = circleArea(3.1); // ok!
cout << "The area is " << a1 << "!!" << endl;
return 0;
}
9
Default parameters
• You can make a parameter optional by supplying a default value:
– All parameters with default values must appear last in the list.
11
Declaration order
• Compiler error: unable to find the circleArea function (!)
– C++ reads the file from top to bottom (unlike some other languages)
int main() {
double a = circleArea(2.5); // call the function
return 0;
}
double circleArea(double r) {
return 3.14159265359 * r * r;
}
12
Function prototypes (1.4)
type name(type name, type name, ..., type name);
– Declare the function (without writing its body) at top of program.
– unlike in Java, you don't write Math. in front of the function name
– see Stanford "gmath.h" library for additional math functionality
14
Plan for Today
• C++ Functions
– Syntax
– Prototypes
– Pass by reference
• Announcements
• Strings
– Common functions and patterns
– C strings vs. C++ strings
15
Pass by Value
int main() {
int x = 17;
int y = 35;
swap(x, y);
cout << x << "," << y << endl; // 17,35
return 0;
}
By default, C++ parameters are copies.
16
Pass by Reference
int main() {
int x = 17;
int y = 35;
swap(x, y);
cout << x << "," << y << endl; // 35,17
return 0;
}
Use “&” to pass the same version.
17
Pass by Reference
int main() {
int x = 17;
int y = 35;
swap(x, y);
cout << x << "," << y << endl; // 35,17
return 0;
}
18
Quadratic exercise quadratic
roots: x = 4 , x = -1
2a
19
Quadratic solution
#include <math.h>
...
/*
* Solves a quadratic equation ax^2 + bx + c = 0,
* storing the results in output parameters root1 and root2.
* Assumes that the given equation has two real roots.
*/
void quadratic(double a, double b, double c,
double& root1, double& root2) {
double d = sqrt(b * b - 4 * a * c);
root1 = (-b + d) / (2 * a);
- ± - 4ac
root2 = (-b - d) / (2 * a); 2
} b b
2a
20
Decomposition
• When solving a large problem, break down the task into functions.
21
Decomposition Example
int main() {
double a, b, c, root1, root2;
getCoefficients(a, b, c);
solveQuadratic(a, b, c, root1, root2);
printRoots(root1, root2);
return 0;
}
24
Announcements
• Assignment 0 due Friday 9/28 11AM
– If you don’t have your own computer, use library or cluster!
• Qt Creator Troubleshooting Session tonight (Wed) 7-9PM @ LaIR
• Required lecture feedback
• Discussion Section signups open 9/27 5PM – 9/30 5PM
• CodeStepByStep
25
CURIS Poster Session
26
WiCS Frosh Interns
WiCS gr a m
t e r n P r o
Frosh In
{ Curious about CS? Looking for a community
on campus? Excited about the WiCS mission?
}
Apply for the WiCS Frosh Intern
Program at bit.ly/wics-frosh-intern-1819
27
CS 581: Media Innovation
CS: 581
MEDIA INNOVATION
28
Stanford Local
Programming Contest
29
Plan for Today
• C++ Functions
– Syntax
– Prototypes
– Pass by reference
• Announcements
• Strings
– Common functions and patterns
– C strings vs. C++ strings
30
Strings (3.1)
#include <string>
...
string s = "hello";
31
Characters
• Characters are values of type char, with 0-based indexes:
string s = "Hi 106X!";
index 0 1 2 3 4 5 6 7
character 'H' 'i' ' ' '1' '0' '6' 'X' '!'
32
Char and cctype (3.3)
• #include <cctype>
– Useful functions to process char values (not entire strings):
Function name Description
isalpha(c) isalnum(c) returns true if the given character is an alphabetic
isdigit(c) isspace(c) character from a-z or A-Z, a digit from 0-9, an
isupper(c) ispunct(c) alphanumeric character (a-z, A-Z, or 0-9), an uppercase
letter (A-Z), a space character (space, \t, \n, etc.), or a
islower(c) punctuation character (. , ; !), respectively
tolower(c) toupper(c) returns lower/uppercase equivalent of a character
// index 012345678901234567890
string s = "Grace Hopper Bot v2.0";
if (isalpha(s[6]) && isnumer(s[18])
&& isspace(s[5]) && ispunct(s[19])) {
cout << "Grace Hopper Smash!!" << endl;
}
33
Operators (3.2)
• Concatenate using + or += :
string s1 = "Dai";
s1 += "sy"; // "Daisy"
34
Member functions (3.2)
Member function name Description
s.append(str) add text to the end of a string
s.compare(str) return -1, 0, or 1 depending on relative ordering
s.erase(index, length) delete text from a string starting at given index
s.find(str) first or last index where the start of str appears in
s.rfind(str) this string (returns string::npos if not found)
s.insert(index, str) add text into a string at a given index
s.length() or s.size() number of characters in this string
s.replace(index, len, str) replaces len chars at given index with new text
s.substr(start, length) or the next length characters beginning at start
s.substr(start) (inclusive); if length omitted, grabs till end of string
if (startsWith(name, "Professor")) {
name += " " + integerToString(workYears) + " years teaching";
}
36
String exercise nameDiamond
37
Exercise solution
void nameDiamond(string& name) {
D
// print top half of diamond DA
for (int i = 1; i <= name.length(); i++) { DAI
cout << name.substr(0, i) << endl; DAIS
DAISY
}
38
String user input (3.1)
• cin reads string input, but only a word at a time:
cout << "Type your name: ";
string name; // Type your name: John Doe
cin >> name; // Hello, John
cout << "Hello, " << name << endl;
40
C vs. C++ strings (3.5)
• C++ has two kinds of strings:
– C strings (char arrays) and C++ strings (string objects)
41
C string bugs
• string s = "hi" + "there"; // C-string + C-string
• string s = "hi" + '?'; // C-string + char
• string s = "hi" + 41; // C-string + int
– C strings can't be concatenated with +.
– C-string + char/int produces garbage, not "hi?" or "hi41".
– This bug usually appears in print statements, and you’ll see partial
strings.
• string s = "hi";
s += 41; // "hi)"
– Adds character with ASCII value 41, ')', doesn't produce "hi41".
• s += integerToString(41); // "hi?41"
• int n = stringToInteger("42"); // 42
– Explicit string <-> int conversion using Stanford library.
43
Recap
• C++ Functions
– Syntax
– Prototypes
– Pass by reference
• Announcements
• Strings
– Common functions and patterns
– C strings vs. C++ strings
44
Overflow (extra) slides
This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
Based on slides created by Keith Schwarz, Julie Zelenski, Marty Stepp, Ashley Taylor, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, and others.
Const parameters
• What if you want to avoid copying a large variable but don't want to
change it?
• Use the const keyword to indicate that the parameter won't be
changed
- Usually used with strings and collections
- Passing in a non-variable (e.g. printString("hello")) does work
void printString(const string& str) {
cout << "I will print this string" << endl;
cout << str << endl;
}
int main() {
printString("This could be a really really long
string");
}
46
Ref param mystery parameterMysteryBCA
int main() {
int a = 4;
int b = 2;
int c = 5;
a = mystery(c, b);
c = mystery(b, a);
cout << a << " " << b << " " << c << endl;
return 0;
}
// A. B. C. D. E.
// 12 2 16 9 2 10 12 2 8 9 2 12 N/A
48
Exercise: BMI BMI
51
What's the output? stringMysteryAB
52