Professional Documents
Culture Documents
Hello World
C++ was created by Bjarne Stroustrup and his team at Bell Laboratories in 1979. Today C++ is
used everywhere even on mars. As the name implies, C++ was derived from the C programming
language; the ++ is the increment operator in C. Bjarne’s goal was to add object-oriented
programming into the C language, which was and still is a language well-respected for its
portability and low-level functionality. It is:
Fast and flexible
Well supported
A language that forces you to think in new and creative ways.
C++ programs are stored in files that usually have the file extension .cpp, which stands for “C Plus
Plus”.
Code 2/5:
#include <iostream> // include libraries
int main() {
// pass string to character out put stream using input operator
std::cout << "Codecademy\n";
}
Code 4/5:
#include <iostream>
int main() {
std::cout << " 1\n";
std::cout << " 2 3\n";
std::cout << " 4 5 6\n";
std::cout << "7 8 9 10\n";
}
Code 5/5:
#include <iostream>
int main() {
std::cout << "Dear Self, dont die lol, 03/07/2019\n";
}
Compile & Execute
C++ is a compiled language, which requires a compiler.
To compile a file you need o type g++ followed by the file name in the terminal:
g++ hello.cpp
It will translate the C++ program hello.cpp and create a machine code file called a.out. To
execute the machine code file, you need to type ./ + the machine code file name in the terminal
./a.out
Code 2/5:
To give the output executable file a specific name, we add -0 file_name after the compile
statement:
g++ hello.cpp –o hello
This will create a machine code file called hello which can be executed using:
./hello
Code 3/5:
Comments:
// single line
/*
Multi
Line
*/
Variables
Int, double, char ‘’, string “”, bool
In C++ variable names consist only of upper/lower case letters, digits and/or underscores.
Code 2/10:
#include <iostream>
int main() {
// Declare a variable
int year;
}
In C++ a single equal sign = does not really mean “equal”. It means “assign”.
Code 3/10:
#include <iostream>
int main() {
// Declare a variable
int year;
// Initialize a variable
year = 2019;
}
Code 4/10:
#include <iostream>
int main() {
int score = 0;
// Declare and initialize a variable here
int year = 2019;
return 0;
}
Code 5/10:
#include <iostream>
int main() {
int score = 0;
// Change score here:
score = 1234 * 99;
std::cout << score << "\n";
}
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. You can use multiple << operators to chain the things you
want to output.
Code 6/10:
#include <iostream>
int main() {
int score = 0;
// Output
std::cout << "Player score: " << score << "\n";
}
Just as cout is used for output, cin is used for input. The output operator >> specifies where the
input goes.
Code 7/10:
#include <iostream>
int main() {
int tip = 0;
std::cout << "Enter tip amount: ";
std::cin >> tip;
std::cout << "You paid " << tip << " dollars.\n";
}
Code 8/10:
#include <iostream>
int main() {
double tempf = 83;
double tempc = (tempf - 32)/1.8;
std::cout << "The temp is " << tempc << " degrees Celsius.\n";
}
Code 9/10:
#include <iostream>
int main() {
double tempf;
double tempc;
int main() {
double height, weight, bmi;
// calculate BMI
bmi = weight / (height*height);
// Output BMI
std::cout << "Your BMI is " << bmi << "\n";
return 0;
}
Conditionals & Logic
Code 2/8:
#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";
}
}
if (condition) {statements}
Code 3/8:
#include <iostream>
int main() {
int grade = 90;
if (grade>60){
std::cout << "Pass";
}
}
Code 4/8:
#include <iostream>
int main() {
int grade = 90;
if (grade != 60) {
std::cout << "Pass\n";
}
}
Code 5/8:
#include <iostream>
int main() {
int grade = 59;
Code 6/8:
#include <iostream>
int main() {
double ph = 4.6;
int main() {
int number = 9;
switch(number) {
case 1 :
std::cout << "Bulbusaur\n";
break;
case 2 :
std::cout << "Ivysaur\n";
break;
case 3 :
std::cout << "Venusaur\n";
break;
case 4 :
std::cout << "Charmander\n";
break;
case 5 :
std::cout << "Charmeleon\n";
break;
case 6 :
std::cout << "Charizard\n";
break;
case 7:
std::cout << "Squirtle";
break;
case 8:
std::cout << "Wartortle";
break;
case 9:
std::cout << "Blastoise";
break;
default :
std::cout << "Unknown\n";
break;
}
}
Code 8/8:
#include <iostream>
int main() {
int planetNumber;
std::string planetName; // You have to use std::string since it's in the std namespace.
double weightKg;
double newWeightKg;
switch (planetNumber){
case 1:
weightKg *= 0.78;
planetName = "Venus";
break;
case 2:
weightKg *= 0.39;
planetName = "Mars";
break;
case 3:
weightKg *= 2.65;
planetName = "Jupiter";
break;
case 4:
weightKg *= 1.17;
planetName = "Saturn";
break;
case 5:
weightKg *= 1.05;
planetName = "Uranus";
break;
case 6:
weightKg *= 1.23;
planetName = "Neptune";
break;
default:
std::cout << "Invalid input\n";
planetName = "Earth";
break;
}
std::cout << "Your weight on planet " << planetName << " is " <<
weightKg << "kg.\n";
}
Logical Operators
&& and, || or, ! not
Code 2/5:
#include <iostream>
int main() {
int hunger = true;
int anger = true;
Code 3/5:
#include <iostream>
int main() {
int day = 6;
Code 4/5:
#include <iostream>
int main() {
bool logged_in = false;
Code 5/5:
#include <iostream>
int main() {
int year;
bool leapYear = false;
if (leapYear){
std::cout << "The year " << year << " is a leap year\n";
} else {
std::cout << "The year " << year << " is not a leap year\n";
}
}
Loops
Code 2/7:
#include <iostream>
int main() {
int pin = 0;
int tries = 0;
if (pin == 1234) {
std::cout << "PIN accepted!\n";
std::cout << "You now have access.\n";
}
}
int main() {
int guess;
int tries = 0;
if (guess == 8) {
std::cout << "You got it!\n";
}
}
Code 4/7:
#include <iostream>
int main() {
int i = 0;
int square = 0;
int main() {
for (int i = 0; i < 10; i++) {
std::cout << "I will not throw paper airplanes in class.\n";
}
}
Code 6/7:
#include <iostream>
int main() {
// Write a for loop here:
for (int i = 99; i > 0; i--){
std::cout << i << " bottles of pop on the wall.\n";
std::cout << "Take one down and pass it around.\n";
std::cout << i-1 << " bottles of pop on the wall.\n\n";
}
Vectors
A vector is a sequence of elements that you can access by index and is dynamically sized.
std::vector lives inside the <vector> header. So you must include <vector> at the top
#include is a pre-processor directive that tells the compiler to include whatever library that
follows.
To create a vector you do:
std::vector<type> name;
The type of the vector cannot be changed after declaration.
Code 2/8:
#include <iostream>
#include <vector>
int main() {
std::vector<double> subway_adult;
Code 3/8:
#include <iostream>
#include <vector>
int main() {
std::vector<double> subway_adult = {800, 1200, 1500};
Code 4/8:
#include <iostream>
#include <vector>
int main() {
std::vector<double> subway_adult = {800, 1200, 1500};
Use .push_back() function to add a new element onto the end (back) of the vector.
Use .pop_back() function to remove elements from the end (back) of the vector. Unlike in other
languages this function does not return the element that is removed.
Code 5/8:
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> last_jedi;
int main() {
std::vector<std::string> grocery = {"Hot Pepper Jam", "Dragon Fruit",
"Brussel Sprouts"};
// Add more
grocery.push_back("Duck");
grocery.push_back("Suck");
grocery.push_back("Fuck");
You can use a for loop to change the value of each element in a vector or add up the elements of
a vector.
Code 7/8:
#include <iostream>
#include <vector>
int main() {
std::vector<double> delivery_order;
delivery_order.push_back(8.99);
delivery_order.push_back(3.75);
delivery_order.push_back(0.99);
delivery_order.push_back(5.99);
Code 8/8:
#include <iostream>
#include <vector>
int main(){
std::vector<int> vec = {2, 4, 3, 6, 1, 9};
int evenTot = 0;
int oddProd = 1;
std::cout << "Sum of even numbers is " << evenTot << "\n";
std::cout << "Product of odd numbers is " << oddProd << "\n";
return 0;
}
Functions
A function is a named block of code that performs a specific task.
Code 2/10:
#include <iostream>
int main() {
// This seeds the random number generator:
srand (time(NULL));
Code 3/10:
return_type function_name( any, parameters, you, have ) {
// Code block here
return output_if_there_is_any;
}
int main() {
// Call your function here:
oscar_wilde_quote();
}
Code 5/10:
#include <iostream>
// Change needs_it_support so that it returns support:
bool needs_it_support() {
bool support;
std::cout << "Hello. IT. Have you tried turning it off and on again?
Enter 1 for yes, 0 for no.\n";
std::cin >> support;
return support;
}
int main() {
// Change the following line to print the function result:
std::cout << needs_it_support();
}
Code 7/10:
#include <iostream>
int main() {
// Original emergency services number
std::string old_emergency_number = "999";
Code 8/10:
#include <iostream>
// Define name_x_times() below:
void name_x_times(std::string name, int x){
while(x>0){
std::cout << name;
x--;
}
}
int main() {
std::string my_name = "Add your name here!";
int some_number = 5; // Change this if you like!
// Call name_x_times() below with my_name and some_number
name_x_times("adfs\n",6);
}
int main() {
introduction("Beyonce", "Knowles");
}
Code 3/7:
#include <iostream>
int main() {
std::cout << average(42.0, 24.0) << "\n";
std::cout << average(1.0, 2.0) << "\n";
}
Code 4/7:
#include <iostream>
#include <cmath>
int main() {
std::cout << tenth_power(0) << "\n";
std::cout << tenth_power(1) << "\n";
std::cout << tenth_power(2) << "\n";
}
Code 5/7:
#include <iostream>
#include <vector>
// Define first_three_multiples() here:
std::vector<int> first_three_multiples(int num){
std::vector<int> multiples;
for(int i = 1; i < 4; i++){
multiples.push_back(num*i);
}
return multiples;
}
int main() {
for (int element : first_three_multiples(8)) {
std::cout << element << "\n";
}
}
Code 6/7:
#include <iostream>
int main() {
std::cout << needs_water(10, false) << "\n";
}
Code 7/7:
#include <iostream>
#include <algorithm>
// Define is_palindrome() here:
bool is_palindrome(std::string text){
std::string textReversed = text; // create clone of text to reverse
// using inbuilt reverse function to reverse the order of elements in
any container
reverse(textReversed.begin(), textReversed.end());
if (text == textReversed){
return true;
} else {
return false;
}
}
int main() {
std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";
}
if (passcode == 0310) {
std::cout << secret_knowledge << "\n";
} else {
std::cout << "Sorry, incorrect!\n";
}
}
int main() {
enter_code(0310);
}
Code 2/9:
#include <iostream>
#include <cmath>
int main() {
std::cout << is_palindrome("racecar") << "\n";
std::cout << tenth_power(3) << "\n";
std::cout << average(8.0, 19.0) << "\n";
}
#include <iostream>
#include <cmath>
if (reversed_text == text) {
return true;
}
return false;
}
Code 3/9:
#include <iostream>
#include "fns.hpp"
int main() {
std::cout << is_palindrome("noon") << "\n";
std::cout << tenth_power(4) << "\n";
std::cout << average(4.0, 7.0) << "\n";
}
#include <iostream>
#include <cmath>
if (reversed_text == text) {
return true;
}
return false;
}
An inline function is a function definition, usually in a header file, qualified by inline. It can help (or
hinder) execution speed by advising the compiler to insert the functions body where the function
call is. You should always use the inline keyword if you are inlining functions in a header, except
for member functions (single line functions that are very short).
Code 4/9:
#include <iostream>
#include <chrono>
#include "night.hpp"
int main() {
// Measure time taken for goodnight1():
std::chrono::high_resolution_clock::time_point start =
std::chrono::high_resolution_clock::now();
std::chrono::high_resolution_clock::time_point end =
std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> time_span = end - start;
inline
std::string goodnight1(std::string thing1) {
return "Goodnight, " + thing1 + ".\n";
}
std::string goodnight2(std::string thing1, std::string thing2);
#include <string>
Code 5/9:
#include <iostream>
#include "coffee.hpp"
int main() {
// coffee black
std::cout << make_coffee();
#include <string>
Overloading
Code 6/9:
#include <iostream>
#include "num_ops.hpp"
int main() {
std::cout << fancy_number(12, 3) << "\n";
std::cout << fancy_number(12, 3, 19) << "\n";
std::cout << fancy_number(13.5, 3.8) << "\n";
}
A template is a C++ tool that allows programmers to add data types as parameters. Comes in
handy for classes and functions. std::string and std::vector are both template-based types.
Templates are entirely created in header files. Templates let you choose the type implementation
right when you call the function. Using templates will slow down the programs compile time, but
speed up the execution time.
Code 8/9:
#include <iostream>
#include "numbers.hpp"
int main() {
std::cout << get_smallest(100, 60) << "\n";
std::cout << get_smallest(2543.2, 3254.3) << "\n";
}
};
Code 2/7:
#include <iostream>
#include "song.hpp"
int main() {
#include <string>
public:
void add_title(std::string new_title);
std::string get_title();
};
#include "song.hpp"
std::string Song::get_title(){
return title;
}
Code 3/7:
#include <iostream>
#include "song.hpp"
int main() {
Song electric_relaxation;
electric_relaxation.add_title("Electric Relaxation");
#include <string>
public:
void add_title(std::string new_title);
std::string get_title();
};
#include "song.hpp"
std::string Song::get_title(){
return title;
}
#include <string>
class Song {
std::string title;
std::string artist;
public:
void add_title(std::string new_title);
std::string get_title();
void add_artist(std::string new_artist);
std::string get_artist();
};
#include "song.hpp"
std::string Song::get_title() {
return title;
}
std::string Song::get_artist(){
return artist;
}
Code 5/7:
#include <iostream>
#include "song.hpp"
int main() {
Song back_to_black("Back to Black","Amy Winehouse");
}
#include <string>
class Song {
std::string title;
std::string artist;
public:
// Add a constructor here:
Song(std::string new_title, std::string new_artist);
std::string get_title();
std::string get_artist();
};
#include "song.hpp"
std::string Song::get_title() {
return title;
}
std::string Song::get_artist() {
return artist;
}
Code 6/7:
#include <iostream>
#include "song.hpp"
int main() {
Song back_to_black("Back to Black", "Amy Winehouse");
}
#include <string>
class Song {
std::string title;
std::string artist;
public:
Song(std::string new_title, std::string new_artist);
// Add a destructor here:
~Song();
std::string get_title();
std::string get_artist();
};
#include "song.hpp"
#include <iostream>
std::string Song::get_title() {
return title;
}
std::string Song::get_artist() {
return artist;
}
int main() {
int soda = 99;
int &pop = soda;
pop++;
std::cout << pop << "\n";
std::cout << soda << "\n";
}
Using references as arguments allows us to modify the argument’s values. Saves computational
cost as you don’t need to make a copy of the argument.
Code 3/9:
#include <iostream>
return i;
}
int main() {
int num = 1;
The const keywords tells the compiler we won’t change something (for constants).
double const pi = 3.14;
Code 4/9:
#include <iostream>
int main() {
int side = 5;
The “address of” operator, &, is used to get the memory address, the location in the memory, of an
object. A memory address is usually denoted in hexadecimal instead of binary for readability and
conciseness.
When & is used in a declaration it is a reference operator,
When & is not used in a declaration is an address operator.
Code 5/9:
#include <iostream>
int main() {
int power = 9000;
// Print power
std::cout << power << "\n";
// Print &power
std::cout << &power << "\n";
}
A pointer variable stores a memory address, pointers are an older mechanism that was inherited
from C.
Code 6/9:
#include <iostream>
int main() {
int power = 9000;
// Create pointer
int* ptr = &power;
// Print ptr
std::cout << ptr << "\n";
}
The dereference operator, *, is used to obtain the value pointed to by a variable, done by
preceding the name with *.
When * is used in a declaration, it is creating a pointer.
When * is not used in a declaration, it is a dereference operator.
Code 7/9:
#include <iostream>
int main() {
int power = 9000;
// Create pointer
int* ptr = &power;
// Print ptr
std::cout << ptr << "\n";
// Print *ptr
std::cout << *ptr << "\n";
}
When we declare a pointer, int* ptr, its content is not initialized, which is dangerous, we need
to initialize a pointer by assigning it a valid address. If we don’t know where we are pointing to we
can use a null pointer, nullptr. (nullptr is a modern replacement to NULL)
Code 8/9:
#include <iostream>
int main() {
int power = 9000;
// Create pointer
int* ptr = nullptr;
// Print ptr
std::cout << ptr << "\n";
}
Code 9/9:
#include <iostream>
int main() {
std::cout << "Dear Self,dont die lol, 03/07/2019\n";
}
Static Members
Code 1/12:
Code 2/12:
Code 3/12:
Code 4/12:
Code 5/12:
Code 6/12:
Code 7/12:
Code 8/12:
Code 9/12:
Code 10/12:
Code 11/12:
Code 12/12: