Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

NOTES Ver.

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.

std::cout << "Hello World!\n";


 std::cout is the “character output stream”. It is pronounced “see-out”.
 << is an operator that comes right after it.
 "Hello World!\n" is what’s being outputted here. You need double
quotes around text. The \n is a special character that indicates a new
line.
 ; is a punctuation that tells the computer that you are at the end of a
statement. It is similar to a period in a sentence.
Things to remember:

 We can use multiple std::cout statements to output multiple


lines.
 Code runs line by line (from top to bottom).
 Note the spacing between the numbers.

C++ is a compiled language. That means that to get a C++ program


to run, you must first translate it from a human-readable form to
something a machine can “understand.” That translation is done by a
program called a compiler.

When you program in C++, you mainly go through 4 phases during


development:

1. Code — writing the program


2. Save — saving the program
3. Compile — compiling via the terminal
4. Execute — executing via the terminal

And repeat (debug the errors if needed).

Compile and Execute

Compile: A computer can only understand machine code.


A compiler can translate the C++ programs that we write into machine
code. To compile a file, you need to type g++ followed by the file
name in the terminal:

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.

Compile and Execute (Naming Executables)

Compile: Sometimes when we compile, we want to give the output


executable file a specific name. To do so, the compile command is
slightly different. We still need to write g++ and the file name in the
terminal. After that, there should be -o and then the name that you
want to give to the executable file:

g++ hello.cpp -o hello


The compiler will then translate the C++ program hello.cpp and
create a machine code file called hello.

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

Programming is often highly collaborative. In addition, our own code


can quickly become difficult to understand when we return to it —
sometimes only a few hours later! For these reasons, it’s often useful
to leave notes in our code for ourselves or other developers.

As we write a C++ program, we can write comments in the code that


the compiler will ignore as our program runs. These comments exist
just for human readers.

Comments can explain what the code is doing, leave instructions for
developers using the code, or add any other useful annotations.

There are two types of code comments in C++:

 A single line comment will comment out a single line and is


denoted with two forward slashes // preceding it:
 // Prints "hi!" to the terminal
std::cout << "hi!";
You can also use a single line comment after a line of code:

std::cout << "hi!"; // Prints "hi!"


 A multi-line comment will comment out multiple lines and is
denoted with /* to begin the comment, and */ to end the
comment:
 /* This is all commented.
 std::cout << "hi!";
None of this is going to run! */

You can output the value by simply adding this code underneath:

std::cout << score << "\n";


Notice how when we want to output a variable, we don’t add double
quotes around its name.

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.

If we have the code below:

int age = 28;

std::cout << "Hello, I am ";


std::cout << age;
std::cout << " years old\n";
It will output:

Hello, I am 28 years old


Notice how we use quotes around the characters in "Hello, I am
" but not in age.

 We use quotes when we want a literal string.


 We don’t use quotes when we refer to the value of something
with a name (like a variable).

So now, is it possible to write the cout statements within a single line?

Yep! You can use multiple << operators to chain the things you want
to output.

For the same code above you can also do:

int age = 28;

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!

std::cout << "Enter your password: ";


std::cin >> password;
The name cin refers to the standard input stream (pronounced “see-
in”, for character input). The second operand of the >> operator (“get
from”) specifies where that input goes.

// first output:

#include <iostream>

int main(int argc, char** argv) {

double height, weight, bmi, height2;

std::cout << "Type in your height (m): ";

std::cin >> height;

std::cout << "Type in your weight (kg): ";

std::cin >> weight;


height2 = (height * height);

bmi = weight / height2;

std::cout << "Your BMI is " << bmi << "\n";

//

Coin Flip Demo

Before we dive deep into the syntax of the if statement, let’s do a


demo!

Here, we have coinflip.cpp program that simulates a coin toss:

 50% of the time, it’s Heads.


 50% of the time, it’s Tails.

#include <iostream>

#include <stdlib.h>

#include <ctime>

int main() {
// Create a number that's 0 or 1

srand (time(NULL));

int coin = rand() % 2;

// If number is 0: Heads

// If it is not 0: Tails

if (coin == 0) {

std::cout << "Heads\n";

} else {

std::cout << "Tails\n";

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.

To have a condition, we need relational operators:

 == 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!

A switch statement provides an alternative syntax that is easier to


read and write. However, you are going to find these less frequently
than if, else if, else in the wild.

A switch statement looks like this:

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;

 The switch keyword initiates the statement and is followed


by (), which contains the value that each case will compare. In
the example, the value or expression of the switch statement
is grade. One restriction on this expression is that it must
evaluate to an integral type (int, char, short, long, long long,
or enum).
 Inside the block, {}, there are multiple cases.
 The case keyword checks if the expression matches the specified
value that comes after it. The value following the first case is 9. If
the value of grade is equal to 9, then the code that follows
the : would run.
 The break keyword tells the computer to exit the block and not
execute any more code or check any other cases inside the code
block.
 At the end of each switch statement, there is
a default statement. If none of the cases are true, then the
code in the default statement will run. It’s essentially
the else part.

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::cout << "Please enter your current earth weight: ";

std::cin >> weight;

std::cout << "\nI have information for the following planets:\n\n";

std::cout << " 1. Venus 2. Mars 3. Jupiter\n";

std::cout << " 4. Saturn 5. Uranus 6. Neptune\n\n";

std::cout << "Which planet are you visiting? ";

std::cin >> x;

if (x == 1) {

weight = weight * 0.78;

} else if (x == 2) {

weight = weight * 0.39;


} else if (x == 3) {

weight = weight * 2.65;

} else if (x == 4) {

weight = weight * 1.17;

} else if (x == 5) {

weight = weight * 1.05;

} else if (x == 6) {

weight = weight * 1.23;

std::cout << "\nYour weight: " << weight << "\n";

//

Introduction to Logical Operators

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.

Logical operators are used to combine two or more conditions. They


allow programs to make more flexible decisions. The result of the
operation of a logical operator is a bool value of either true or false.

There are three logical operators that we will cover:

 &&: the and logical operator


 ||: the or logical operator
 !: the not logical operator

// Third output:

#include <iostream>

int main() {

int y = 0;

std::cout << "Enter year: ";

std::cin >> y;

if (y < 1000 || y > 9999) {

std::cout << "Invalid entry.\n";

else if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {

std::cout << y;

std::cout << " falls on a leap year.\n";

} else {

std::cout << y;

std::cout << " is not a leap year.\n";


}

//

Introduction to Loops

A loop is a programming tool that repeats some code or a set of


instructions until a specified condition is reached. As a programmer,
you’ll find that you rely on loops all the time! You’ll hear the generic
term “iterate” when referring to loops; iterate simply means “to
repeat”.

When we see that a process has to repeat multiple times in a row, we


write a loop. Loops allow us to create efficient code that automates
processes to make scalable, manageable programs.

While Loop Demo

So first up… the while loop!

Before we dive deep into the syntax of the while loop, let’s do a
demo.

Inside enter_pin.cpp, we have a program that asks and checks for a


password. It uses a while loop to ask the user for the password over
and over again.

// Demo output:

#include <iostream>

int main() {
int pin = 0;

int tries = 0;

std::cout << "BANK OF CODECADEMY\n";

std::cout << "Enter your PIN: ";

std::cin >> pin;

while (pin != 1234 && tries <= 3) {

std::cout << "Enter your PIN: ";

std::cin >> pin;

tries++;

if (pin == 1234) {

std::cout << "PIN accepted!\n";

std::cout << "You now have access.\n";

//

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.

In other words, instead of executing if something is true, it


executes while that thing is true.

while (guess != 8) {

std::cout << "Wrong guess, try again: ";


std::cin >> guess;

}
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.

For Loop Demo

Iterating over a sequence of numbers is so common that C++, like


most other programming languages, has a special syntax for it.

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:

for (int i = 0; i < 20; i++)


{

std::cout << "I will not throw paper airplanes in


class.\n";

}
Let’s take a closer look at the first line:

for (int i = 0; i < 20; i++)


There are three separate parts to this separated by ;:

 The initialization of a counter: int i = 0


 The continue condition: i < 20
 The change in the counter (in this case an increment): i++

So here we are creating a variable i that starts from 0. We will repeat


the code inside over and over again when i is less than 20. At the end
the for loop, we are adding 1 to i using the ++ operator.

Introduction to Bugs

“First actual case of bug being found.”

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.

On your programming journey, you are destined to encounter


innumerable red errors. Some even say, that debugging is over 75% of
the development time. But what makes a programmer successful isn’t
avoiding errors, it’s knowing how to find the solution.

In C++, there are many different ways of classifying errors, but they
can be boil down to four categories:

 Compile-time errors: Errors found by the compiler.


 Link-time errors: Errors found by the linker when it is trying to
combine object files into an executable program.
 Run-time errors: Errors found by checks in a running program.
 Logic errors: Errors found by the programmer looking for the
causes of erroneous results.

In this mini-lesson, we will be looking at different errors and different


error messages, and we’ll teach you how to think about errors in your
code a little differently.

Compile-time Errors

When we are writing C++ programs, the compiler is our first line of
defense against errors.

There are two types of compile-time errors:

 Syntax errors: Errors that occur when we violate the rules of


C++ syntax.
 Type errors: Errors that occur when there are mismatch between
the types we declared.

Some common syntax errors are:

 Missing semicolon ;
 Missing closing parenthesis ), square bracket ], or curly brace }

Some common type errors are:

 Forgetting to declare a variable


 Storing a value into the wrong type

Here’s an example of a compile-time error message:


The compiler will tell us where (line number) it got into trouble and its
best guess as to what is wrong.

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.

As our program gets bigger, it is good practice to divide the program


into separate files. After compiling them, the linker takes those
separate object files and combines them into a single executable file.
Link-time errors are found by the linker when it is trying to combine
object files into an executable file.

Some common link-time errors:

 Using a function that was never defined (more on this later)


 Writing Main() instead of main()

Here’s an example of a link-time error message:


These errors are more hard to find, but remember, Google is your
friend! Here, a good Google search would be: “C++ undefined
reference to main”.

Run-time Errors

If our program has no compile-time errors and no link-time errors, it’ll


run. This is where the fun really starts.

Errors which happen during program execution (run-time) after


successful compilation are called run-time errors. Run-time errors
occur when a program with no compile-time errors and link-time
errors asks the computer to do something that the computer is unable
to reliably do.

It happens after we give the ./ execute command:

./a.out
Some common run-time errors:

 Division by zero also known as division error. These types of error


are hard to find as the compiler doesn’t point to the line at which
the error occurs.
 Trying to open a file that doesn’t exist

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

Once we have removed the compile-time errors, link-time errors, and


run-time errors, the program runs successfully. But sometimes, the
program doesn’t do what we want it to do or no output is produced.
Hmmm…

These types of errors which provide incorrect output, but appears to


be error-free, are called logical errors. These are one of the most
common errors that happen to beginners and also usually the most
difficult to find and eliminate.

Logical errors solely depend on the logical thinking of the


programmer. Your job now is to figure out why the program didn’t do
what you wanted it to do.

Some common logic errors:

 Program logic is flawed


 Some “silly” mistake in an if statement or a for/while loop

Note: Logic errors don’t have error messages. Sometimes,


programmers use a process called test-driven development (TDD), a
way to give logic errors error messages and save yourself a lot of
headaches!
Finding bugs is a huge part of a programmer’s life. Don’t be
intimidated by them… embrace them. Errors in your code mean you’re
trying to do something cool!

In this lesson, we have learned about the four types of C++ errors:

 Compile-time errors: Errors found by the compiler.


 Link-time errors: Errors found by the linker when it is trying to
combine object files into an executable program.
 Run-time errors: Errors found by checks in a running program.
 Logic errors: Errors found by the programmer looking for the
causes of erroneous results.

Remember, Google and Stack Overflow are a programmer’s best


friends. For some more motivation, check out this blog post: Thinking
About Errors in Your Code Differently.

// fourth output (already debugged):

#include <iostream>

#include <stdlib.h>

#include <ctime>

int main() {

srand (time(NULL));

int fortune = rand() % 10;

if (fortune == 0) {

std::cout << "Flattery will go far tonight.\n";

} else if (fortune == 1) {
std::cout << "Don't behave with cold manners.\n";

} else if (fortune == 2) {

std::cout << "May you someday be carbon neutral\n";

} else if (fortune == 3) {

std::cout << "You have rice in your teeth.\n";

} else if (fortune == 4) {

std::cout << "A conclusion is simply the place where you got tired
of thinking.\n";

} else if (fortune == 5) {

std::cout << "No snowflake feels responsible in an avalanche.\n";

} else if (fortune == 6) {

std::cout << "He who laughs last is laughing at you.\n";

} else if (fortune == 7) {

std::cout << "If you look back, you'll soon be going that way.\n";

} else if (fortune == 8) {

std::cout << "You will die alone and poorly dressed.\n";

} else if (fortune == 9) {

std::cout << "The fortune you seek is in another cookie.\n";

}
}

//

Introduction to Vectors

To do just about anything of interest in a program, we need a group


of data to work with.

For example, our program might need:

 A list of Twitter’s trending tags


 A set of payment options for a car
 A catalog of eBooks read over the last year

The need for storing a collection of data is endless.

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.

A vector is a sequence of elements that you can access by index.

Creating a Vector

The std::vector lives in the <vector> header. So first, we need to


add this line of code at the top of the program:

#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.

And the syntax to create a vector looks like:


std::vector<type> name;
So to define a vector of ints called calories_today:

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

Now we know how to create a vector, we can also initialize a vector,


giving it values, as we are creating it in the same line.

For example, instead of just creating a double vector


named location:

std::vector<double> location;
We can create and initialize location with specific values:

std::vector<double> location = {42.651443, -73.749302};


Here, we are storing a latitude and a longitude.

So it would look something like this:

Another way we can initialize our vector is by presizing, or setting the


size.

Suppose we want to create and initialize a vector with two elements.


However, we don’t know what values we want to add yet:

std::vector<double> location(2);
Here, we are creating a double vector and setting the initial size to
two using parentheses.

It would look something like this:

Because 0.0 is the default value for double.

Index

Now that we have a vector, how do we access an individual element?


This is where index comes into play.

An index refers to an element’s position within an ordered list. Vectors


are 0-indexed, meaning the first element has index 0, the second index
1, and so on.

For example, suppose we have a char vector with all the vowels:

std::vector<char> vowels = {'a', 'e', 'i', 'o', 'u'};


It should look something like this:

 The character at index 0 is 'a'.


 The character at index 1 is 'e'.
 The character at index 2 is 'i'.
 The character at index 3 is 'o'.
 The character at index 4 is 'u'.

To output each of the elements, we can do:


std::cout << vowels[0] << "\n";
std::cout << vowels[1] << "\n";
std::cout << vowels[2] << "\n";
std::cout << vowels[3] << "\n";
std::cout << vowels[4] << "\n";
Using the notation vector[index] with square brackets after the
vector name and the element’s index number inside.

This will output:

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:

std::vector<std::string> dna = {"ATG", "ACG"};


It would look like:

We can add elements using .push_back():

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.

The vector would now look like:

because CTG is removed!

Note: If you have programmed in other languages, be aware


that .pop_back() has no return value in C++.

.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.

For example, suppose we have a std::string vector with Sonny’s


grocery list:

std::vector<std::string> grocery = {"Hot Pepper Jam",


"Dragon Fruit", "Brussel Sprouts"};
It should look something like this:

 The string at index 0 is "Hot Pepper Jam".


 The string at index 1 is "Dragon Fruit".
 The string at index 2 is "Brussel Sprouts".

std::cout << grocery.size() << "\n";


will return

3
Notice how nothing goes in the parentheses.

Operations

So what happens when you want to change each of the values within a
vector?

You can use a for loop!

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.

for (int i = 0; i < vector.size(); i++) {

vector[i] = vector[i] + 10;

}
This will change the vector to:

Here, we incremented i from 0 to vector.size(), which is 3. During


each iteration, we are adding 10 to the element at position i:

 When i = 0, we added 10 to vector[0]


 When i = 1, we added 10 to vector[1]
 When i = 2, we added 10 to vector[2]

You might also like