Professional Documents
Culture Documents
NOTES VerC++
NOTES VerC++
C++:
C++ programs are stored in files which usually have the file
extension .cpp, which simply stands for “C Plus Plus”.
High five! We just got your first program to run.
C++, like most programming languages, runs line by line, from top to
bottom. Here is the structure of a C++ program:
In between the curly braces is what we are going to focus on for now.
g++ hello.cpp
The compiler will then translate the C++ program hello.cpp and
create a machine code file called a.out.
Execute: To execute the new machine code file, all you need to do is
type ./ and the machine code file name in the terminal:
./a.out
The executable file will then be loaded to computer memory and the
computer’s CPU (Central Processing Unit) executes the program one
instruction at a time.
Execute: To execute the new machine code file, all you need to do is
type ./ and the machine code file name in the terminal:
./hello
The executable file will then be loaded to computer memory and the
computer’s CPU will execute the program one instruction at a time.
Comments
Comments can explain what the code is doing, leave instructions for
developers using the code, or add any other useful annotations.
You can output the value by simply adding this code underneath:
Chaining
Now that we have outputted a variable and have also outputted things
using multiple couts. Let’s take a closer look at cout again.
Yep! You can use multiple << operators to chain the things you want
to output.
std::cout << "Hello, I am " << age << " years old\n";
This is called chaining.
User Input
Like we mentioned in the introduction, another way to assign a value
to a variable is through user input. A lot of times, we want the user of
the program to enter information for the program.
We have cout for output, and there is something called cin that’s
used for input!
// first output:
#include <iostream>
//
#include <iostream>
#include <stdlib.h>
#include <ctime>
int main() {
// Create a number that's 0 or 1
srand (time(NULL));
// If number is 0: Heads
// If it is not 0: Tails
if (coin == 0) {
} else {
The code on lines 9 and 10 show how you can create a random
number during each execution: coin will be either 0 or 1.
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Switch Statement
Now that we know how if, else if, else work, we can write
programs that have multiple outcomes. Programs with multiple
outcomes are so common that C++ provides a special statement for
it… the switch statement!
switch (grade) {
case 9:
std::cout << "Freshman\n";
break;
case 10:
std::cout << "Sophomore\n";
break;
case 11:
std::cout << "Junior\n";
break;
case 12:
std::cout << "Senior\n";
break;
default:
std::cout << "Invalid\n";
break;
In the code above, suppose grade is equal to 10, then the output
would be “Sophomore”.
Note: Without the break keyword at the end of each case, the
program would execute the code for the first matching case
and all subsequent cases, including the default code. This behavior is
different from if / else conditional statements which execute only
one block of code.
// Second Output:
#include <iostream>
int main() {
double weight;
int x;
std::cin >> x;
if (x == 1) {
} else if (x == 2) {
} else if (x == 4) {
} else if (x == 5) {
} else if (x == 6) {
//
Often, when we are trying to create a control flow for our program,
we’ll encounter situations where the logic cannot be satisfied with a
single condition.
// Third output:
#include <iostream>
int main() {
int y = 0;
std::cin >> y;
std::cout << y;
} else {
std::cout << y;
//
Introduction to Loops
Before we dive deep into the syntax of the while loop, let’s do a
demo.
// Demo output:
#include <iostream>
int main() {
int pin = 0;
int tries = 0;
tries++;
if (pin == 1234) {
//
The while loop looks very similar to an if statement. And just like
an if statement, it executes the code inside of it if the condition
is true.
However, the difference is that the while loop will continue to execute
the code inside of it, over and over again, as long as the condition
is true.
while (guess != 8) {
}
In this example, while guess is not equal to 8, the program will keep
on asking the user to input a new number. It will exit the while loop
once the user types in 8 and then the program will continue.
When we know exactly how many times we want to iterate (or when
we are counting), we can use a for loop instead of a while loop:
}
Let’s take a closer look at the first line:
Introduction to Bugs
The story goes that on September 9th, 1947, computer scientist Grace
Hopper found a moth in the Harvard Mark II computer’s log book and
reported the world’s first literal computer bug. However, the term
“bug”, in the sense of technical error, dates back at least to 1878 and
with Thomas Edison.
In C++, there are many different ways of classifying errors, but they
can be boil down to four categories:
Compile-time Errors
When we are writing C++ programs, the compiler is our first line of
defense against errors.
Missing semicolon ;
Missing closing parenthesis ), square bracket ], or curly brace }
Link-time Errors
Sometimes the code compiles fine, but there is still a message because
the program needs some function or library that it can’t find. This is
known as a link-time error.
Run-time Errors
./a.out
Some common run-time errors:
There is no way for the compiler to know about these kinds of errors
when the program is compiled.
Here’s an example of a run-time error message:
Logic Errors
In this lesson, we have learned about the four types of C++ errors:
#include <iostream>
#include <stdlib.h>
#include <ctime>
int main() {
srand (time(NULL));
if (fortune == 0) {
} else if (fortune == 1) {
std::cout << "Don't behave with cold manners.\n";
} else if (fortune == 2) {
} else if (fortune == 3) {
} else if (fortune == 4) {
std::cout << "A conclusion is simply the place where you got tired
of thinking.\n";
} else if (fortune == 5) {
} else if (fortune == 6) {
} else if (fortune == 7) {
std::cout << "If you look back, you'll soon be going that way.\n";
} else if (fortune == 8) {
} else if (fortune == 9) {
}
}
//
Introduction to Vectors
We are familiar with data types like int and double, but how do we
store a group of ints or a group of doubles?
In this lesson, we will start with one of the simplest, and arguably the
most useful, ways of storing data in C++: a vector.
Creating a Vector
#include <vector>
For review, #include is a preprocessor directive that tells the compiler
to include whatever library that follows. In our case that is the
standard vector library.
std::vector<int> calories_today;
Inside the angle brackets is the data type of the vector. After the angle
brackets is the name of the vector.
Note: The type of the vector (i.e., what data type is stored inside)
cannot be changed after the declaration.
Initializing a Vector
std::vector<double> location;
We can create and initialize location with specific values:
std::vector<double> location(2);
Here, we are creating a double vector and setting the initial size to
two using parentheses.
Index
For example, suppose we have a char vector with all the vowels:
a
e
i
o
u
Often, we start with a vector that’s either empty or a certain length. As
we read or compute data we want, we can grow the vector as needed.
.push_back()
To add a new element to the “back”, or end of the vector, we can use
the .push_back() function.
For example, suppose we have a vector called dna with three letter
codes of nucleotides:
dna.push_back("GTG");
dna.push_back("CTG");
So now dna would look like:
.pop_back()
You can also remove elements from the “back” of the vector
using .pop_back().
dna.pop_back();
Notice how nothing goes inside the parentheses.
.size()
<std::vector> not only stores the elements; it also stores the size of
the vector:
The .size() function returns the number of elements in the vector.
3
Notice how nothing goes in the parentheses.
Operations
So what happens when you want to change each of the values within a
vector?
For example, suppose we have an int vector that looks like this:
You can write a for loop that iterates from 0 to vector.size(). And
here’s the cool part: you can use the counter of the for loop as the
index! Woah.
}
This will change the vector to: