Lecture 2 Programming Fundamentals in C++
Lecture 2 Programming Fundamentals in C++
Fundamentals in C++
What programming language are you most
comfortable with?
(put your answers the chat)
Object-Oriented
Roadmap Programming
C++ basics
Implementation
User/client
vectors + grids arrays
dynamic memory
stacks + queues
management
sets + maps linked data structures
real-world
Diagnostic algorithms
C++ basics
Implementation
User/client
vectors + grids arrays
dynamic memory
stacks + queues
management
sets + maps linked data structures
real-world
Diagnostic algorithms
What’s next?
Why C++?
Review: How is C++ different from other languages?
● C++ is a compiled language (vs. interpreted)
○ This means that before running a C++ program, you must first compile it to
machine code.
Review: How is C++ different from other languages?
● C++ is a compiled language (vs. interpreted)
● If you’re coming from a language like Python, the syntax will take some getting
used to.
○ Like learning the grammar and rules of a new language, typos are
expected. But don’t let this get in the way of working toward literacy!
Review: How is C++ different from other languages?
● C++ is a compiled language (vs. interpreted)
● If you’re coming from a language like Python, the syntax will take some getting
used to.
Zoom Poll!
Where does C++ rank among the popular programming
languages of the world?
C++ Overview
If someone claims to have the perfect programming language,
he is either a fool or a salesman or both.
– Bjarne Stroustrup, Inventor of C++
C++ History
● C++ is a high-performance, robust (and complex) language built on top of the C
programming language (originally named C with Classes)
○ Bjarne Stroustrup, the inventor of C++, chose to build on top of C because it was fast, powerful,
and widely-used
C++ History
● C++ is a high-performance, robust (and complex) language built on top of the C
programming language (originally named C with Classes)
○ Bjarne Stroustrup, the inventor of C++, chose to build on top of C because it was fast, powerful,
and widely-used
● C++ has been an object-oriented language from the beginning
○ We will spend the middle portion of this class talking about the paradigm of object-oriented
programming
C++ History
● C++ is a high-performance, robust (and complex) language built on top of the C
programming language (originally named C with Classes)
○ Bjarne Stroustrup, the inventor of C++, chose to build on top of C because it was fast, powerful,
and widely-used
● C++ has been an object-oriented language from the beginning
○ We will spend the middle portion of this class talking about the paradigm of object-oriented
programming
● C++ is quite mature and has become complex enough that it is challenging to
master the language
○ Our goal in this class will be to help you become literate in C++ as a second programming
language
C++ History
● C++ is a high-performance, robust (and complex) language built on top of the C
programming language (originally named C with Classes)
○ Bjarne Stroustrup, the inventor of C++, chose to build on top of C because it was fast, powerful,
and widely-used
● C++ has been an object-oriented language from the beginning
○ We will spend the middle portion of this class talking about the paradigm of object-oriented
programming
● C++ is quite mature and has become complex enough that it is challenging to
master the language
○ Our goal in this class will be to help you become literate in C++ as a second programming
language
C++ Benefits and Drawbacks
Benefits
C++ Benefits and Drawbacks
Benefits
● C++ is fast
○ Get ready for the Python vs C++ speed
showdown during Assignment 1!
C++ Benefits and Drawbacks
Benefits
● C++ is fast
○ Get ready for the Python vs C++ speed
showdown during Assignment 1!
● C++ is popular
○ Many companies and research projects
use C++ and it is common for coding
interviews to be conducted in C++
C++ Benefits and Drawbacks
Benefits
● C++ is fast
○ Get ready for the Python vs C++ speed
showdown during Assignment 1!
● C++ is popular
○ Many companies and research projects
use C++ and it is common for coding
interviews to be conducted in C++
● C++ is powerful
○ C++ brings you closer to the raw
computing power that your computer
has to offer
C++ Benefits and Drawbacks
Benefits Drawbacks
● C++ is fast
○ Get ready for the Python vs C++ speed
showdown during Assignment 1!
● C++ is popular
○ Many companies and research projects
use C++ and it is common for coding
interviews to be conducted in C++
● C++ is powerful
○ C++ brings you closer to the raw
computing power that your computer
has to offer
C++ Benefits and Drawbacks
Benefits Drawbacks
cout << "Hello, World!" << endl; // everything past the double-slash is a comment
● Multi-line comments
*/
Includes
● Utilizing code written by other programmers is one of the most powerful things
that you can do when writing code.
● In order to make the compiler aware of other code libraries or other code files
that you want to use, you must include a header file. There are two ways that
you can do so:
○ #include <iostream>
■ Use of the angle bracket operators is usually reserved for code from the C++ Standard
library
○ #include "console.h"
■ Use of the quotes is usually reserved for code from the Stanford C++ libraries, or code in
files that you have written yourself
Console Output
● The console is the main venue that we will use in this class to communicate
information from a program to the user of the program.
Console Output
● The console is the main venue that we will use in this class to communicate
information from a program to the user of the program.
● In C++, the way that you get information to the console is by using the cout
keyword and angle bracket operators (<<).
cout << "The answer to life, the universe, and everything is " << 42 << "." << endl;
Console Output
● The console is the main venue that we will use in this class to communicate
information from a program to the user of the program.
● In C++, the way that you get information to the console is by using the cout
keyword and angle bracket operators (<<).
● The endl is necessary to put the cursor on a different line. Here is an example
with and without the endl keyword.
cout << "This is some text followed by endl." << endl;
cout << "This is more text.";
cout << "We want to go to the next line here, too" << endl;
cout << "We made it to the next line." << endl;
Console Output
● The console is the main venue that we will use in this class to communicate
information from a program to the user of the program.
● In C++, the way that you get information to the console is by using the cout
keyword and angle bracket operators (<<).
● The endl is necessary to put the cursor on a different line. Here is an example
with and without the endl keyword.
cout << "This is some text followed by endl." << endl;
cout << "This is more text.";
cout << "We want to go to the next line here, too" << endl;
cout << "We made it to the next line." << endl;
106 classNum
94.7 tuesdayTemp
Variables
● A way for code to store information by associating a value with a name
int
int a; // declare a new integer variable
a
Typed Variables
5
int
int a; // declare a new integer variable
a = 5; // initialize the variable value
a
Typed Variables
5
int
int a; // declare a new integer variable
a = 5; // initialize the variable value
char
char b = 'x'; // b is a char
("character") a 'x'
b
Typed Variables
5
int
int a; // declare a new integer variable
a = 5; // initialize the variable value
char
char c = 'x'; // b is a char ("character")
a 'x'
double d = 1.06; // d is a double, a type
used to represent decimal numbers
c
double
1.06
d
Typed Variables
5
int
int a; // declare a new integer variable
a = 5; // initialize the variable value
char
char c = 'x'; // b is a char ("character")
a 'x'
double d = 1.06; // d is a double, a type
used to represent decimal numbers
string s = "this is a C++ string"; c
double
1.06
string
"this is a
d C++ string"
s
Typed Variables
5
int
int a; // declare a new integer variable
a = 5; // initialize the variable value
char
char c = 'x'; // b is a char ("character")
a 'x'
double d = 1.06; // d is a double, a type
used to represent decimal numbers
string s = "this is a C++ string"; c
double a = 4.2; // ERROR! You cannot
double
redefine a variable to be another type
1.06
string
"this is a
d C++ string"
s
Typed Variables
5
int
int a; // declare a new integer variable
a = 5; // initialize the variable value
char
char c = 'x'; // b is a char ("character")
a 'x'
double d = 1.06; // d is a double, a type
used to represent decimal numbers
string s = "this is a C++ string"; c
double a = 4.2; // ERROR! You cannot
double
redefine a variable to be another type
int a = 12; // ERROR! You do not need the
1.06
type when re-assigning a variable
string
"this is a
d C++ string"
s
Typed Variables
12
int
int a; // declare a new integer variable
a = 5; // initialize the variable value
char
char c = 'x'; // b is a char ("character")
a 'x'
double d = 1.06; // d is a double, a type
used to represent decimal numbers
string s = "this is a C++ string"; c
double a = 4.2; // ERROR! You cannot
double
redefine a variable to be another type
int a = 12; // ERROR! You do not need the
1.06
type when re-assigning a variable
string
"this is a
a = 12; // this is okay, updates variable
value
d C++ string"
s
Functions and
Parameters
Anatomy of a function
parameters/
arguments
Anatomy of a function
Definition
parameter(s)
parameters/ One or more variables that your
arguments function expects as input
Anatomy of a function
Definition
argument(s)
The values passed into your
parameters/ function and assigned to its
arguments parameter variables
Anatomy of a function
return value
Anatomy of a function
Definition
return value
The value that your function return value
hands back to the “calling”
function
Anatomy of a function
function
prototype
Anatomy of a function
returnType functionName(varType parameter1, varType parameter2, ...);
function name
Anatomy of a function
returnType functionName(varType parameter1, varType parameter2, ...);
input expected
(parameters)
Anatomy of a function
returnType functionName(varType parameter1, varType parameter2, ...);
output expected
(return type)
Anatomy of a function
returnType functionName(varType parameter1, varType parameter2, ...);
function
definition
Anatomy of a function
returnType functionName(varType parameter1, varType parameter2, ...);
returned value
Function Example
double average(double a, double b){
double sum = a + b;
return sum / 2;
}
int main(){
double mid = average(10.6, 7.2);
cout << mid << endl;
return 0;
}
Function Example
double average(double a, double b){
double sum = a + b; Order matters! A
return sum / 2;
} function must always
be defined before it is
int main(){ called.
double mid = average(10.6, 7.2);
cout << mid << endl;
return 0;
}
Function Example
double average(double a, double b){
double sum = a + b;
}
return sum / 2;
callee
(called function)
int main(){
double mid = average(10.6, 7.2);
cout << mid << endl;
return 0; caller
} (calling function)
Function Example
double average(double a, double b){
double sum = a + b;
return sum / 2; parameters
}
return value
int main(){
double mid = average(10.6, 7.2);
cout << mid << endl;
return 0; arguments
}
Function Example
double average(double a, double b){
double
double sum = a + b;
return sum / 2; 10.6 a
}
double
int main(){
7.2 b
double mid = average(10.6, 7.2);
cout << mid << endl;
double
return 0; 17.8 sum
}
These variables only
Function Example
exist inside average()!
double average(double a, double b){
double
double sum = a + b;
return sum / 2; 10.6 a
}
double
int main(){
7.2 b
double mid = average(10.6, 7.2);
cout << mid << endl;
double
return 0; 17.8 sum
}
Function Example
double average(double a, double b){
double sum = a + b;
return sum / 2;
}
double
8.9
int main(){
double mid = average(10.6, 7.2); mid
cout << mid << endl;
return 0;
}
Function Example
double average(double a, double b){
This variable only
double sum = a + b; exists inside main()!
return sum / 2;
}
double
8.9
int main(){
double mid = average(10.6, 7.2); mid
cout << mid << endl;
return 0;
}
Pass by Value
// C++:
#include<iostream>
using namespace std; Zoom Poll!
int doubleValue(int x) {
x *= 2;
}
return x;
What is the console
int main() { output of this block of
int myValue = 5;
int result = doubleValue(myValue); code?
cout << "myValue: " << myValue << " ";
cout << "result: " << result << endl;
}
Pass by Value
// C++:
#include<iostream>
using namespace std;
myValue: 5 result: 10
int doubleValue(int x) {
x *= 2;
return x;
}
int main() {
int myValue = 5;
Why is this the case?
int result = doubleValue(myValue);
a == b a is equal to b
a != b a is not equal to b
Conditional Statements
● The C++ if statement tests a boolean expression and runs a block of code if the expression is true, and, optionally, runs a
different block of code if the expression is false. The if statement has the following format:
○ if (expression) {
statements if expression is true Note: The parentheses around
} else { expression are required.
statements if expression is false
}
Conditional Statements
● The C++ if statement tests a boolean expression and runs a block of code if the expression is true, and, optionally, runs a
different block of code if the expression is false. The if statement has the following format:
○ if (expression) {
statements if expression is true Note: The parentheses around
} else { expression are required.
statements if expression is false
}
● Additional else if statements can be used to check for additional conditions as well
○ if (expression1) {
statements if expression1 is true
} else if (expression2) {
statements if expression2 is true
} else {
statements if neither expression1 nor expression2 is true
}
while loops
● Loops allow you to repeat the execution of a certain block of code multiple
times
while loops
● Loops allow you to repeat the execution of a certain block of code multiple
times
● while loops are great when you want to continue executing something until a
certain condition is met and you don't know exactly how many times you want
to iterate for
while loops
● Loops allow you to repeat the execution of a certain block of code multiple
times
● while loops are great when you want to continue executing something until a
certain condition is met and you don't know exactly how many times you want
to iterate for
while (expression) {
statement;
statement;
... Execution continues until
} expression evaluates to false
while loops
● Loops allow you to repeat the execution of a certain block of code multiple
times
● while loops are great when you want to continue executing something until a
certain condition is met and you don't know exactly how many times you want
to iterate for
Output:
while (expression) { int i = 0; 0
while (i < 5) {
statement; 1
statement; cout << i << endl;
... i++; 2
} } 3
4
while loops
● Loops allow you to repeat the execution of a certain block of code multiple
times
● while loops are great when you want to continue executing something until a
certain condition is met and you don't know exactly how many times you want
to iterate for
Output:
while (expression) { int i = 0; 0
while (i < 5) {
statement; 1
statement; cout << i << endl;
... i++; 2
} } 3
Note: The i++ increments the variable i by 1, and is the reason C++ got its name!
4
(and there is a corresponding decrement operator, --, as in i--).
for loops
● for loops are great when you have a known, fixed number of times that you
want to execute a block of code
for loops
● for loops are great when you have a known, fixed number of times that you
want to execute a block of code
● for loop syntax in C++ can look a little strange, let's investigate!
for loops
● for loops are great when you have a known, fixed number of times that you
want to execute a block of code
E.g., int i = 0.
for loops
● for loops are great when you have a known, fixed number of times that you
want to execute a block of code
E.g., i < 3.
for loops
● for loops are great when you have a known, fixed number of times that you
want to execute a block of code
E.g., i++.
for loops
● for loops are great when you have a known, fixed number of times that you
want to execute a block of code
int main() {
/* TODO: Your code goes here! */
return 0;
}
C++
Try it for yourself! def main():
for i in range(10, 0, -1):
print(i)
print ("Liftoff")
Write a program that prints out the
if __name__ == "__main__":
calls for a spaceship that is about to main()
return 0;
Rooms!
}
C++
How do we test code in
CS106B?
Testing
Software and cathedrals are much the same – first we build them,
then we pray.
– Sam Redwine
Why is testing important?
Why is testing important?
Source: https://royal.pingdom.com/10-historical-software-bugs-with-extreme-consequences/
Why is testing important?
In 1996, a European Ariane 5 rocket
was set to deliver a payload of
satellites into Earth orbit, but problems
with the software caused the launch
rocket to veer off its path a mere 37
seconds after launch. The problem was
the result of code reuse from the
launch system’s predecessor, Ariane 4,
which had very different flight
conditions from Ariane 5.
Source: https://royal.pingdom.com/10-historical-software-bugs-with-extreme-consequences/
Why is testing important?
A 2002 study commissioned by the
National Institute of Standards and
Technology (referred to here) found
that software bugs cost the U.S.
economy $59.5 billion every year
(imagine the global costs…). The
study estimated that more than a
third of that amount, $22.2 billion,
could be eliminated by improved
testing.
Source: https://royal.pingdom.com/10-historical-software-bugs-with-extreme-consequences/
Why is testing important?
● Testing can save money
● Consider:
○ Basic use cases
○ Edge cases
Testing strategies
● Write tests that cover a wide variety of use cases for your function!
● Consider:
○ Basic use cases
○ Edge cases
Definition
edge case
Uses of your function/program that
represent extreme situations
Testing strategies
● Write tests that cover a wide variety of use cases for your function!
For example, if your function takes in an
● Consider: integer parameter, test what happens if the
○ Basic use cases value that is passed in negative, zero, a large
○ Edge cases
positive number, etc!
Definition
edge case
Uses of your function/program that
represent extreme situations
SimpleTest
What is SimpleTest?
● SimpleTest is a C++ library developed by some of the lecturers here at
Stanford that allows standalone, C++ unit testing
● For those of you coming from CS106A in Python, this is similar in
functionality to the doctest infrastructure that you learned
● We will see SimpleTest a lot this quarter! You will learn how to write
good, comprehensive suites of tests using this library, starting from the
very first assignment.
How does SimpleTest work?
#include "testing/SimpleTest.h"
#include "all-examples.h"
int main()
{
if (runSimpleTests(SELECTED_TESTS)) {
return 0;
}
return 0; NO_TESTS
} SELECTED_TESTS
ALL_TESTS
How does SimpleTest work?
main.cpp all-examples.cpp