You are on page 1of 21

Optional: Introduction to Computer Science

– MIT Lecture
https://www.youtube.com/watch?v=k6U-i4gXkLM

1.2 — Comments
A comment is a programmer-readable note that is inserted directly into the source code of the program.
Comments are ignored by the compiler and are for the programmer’s use only.

To comment out a single line of code, simply use the // style comment to turn a line of code into a comment
temporarily:

Uncommented out:

1     std::cout << 1;

Commented out:

1 //    std::cout << 1;

To comment out a block of code, use // on multiple lines of code, or the /* */ style comment to turn the block
of code into a comment temporarily.

Uncommented out:

1     std::cout << 1;

2     std::cout << 2;

3     std::cout << 3;

Commented out:

1 //    std::cout << 1;

2 //    std::cout << 2;

3 //    std::cout << 3;
or

1 /*

2     std::cout << 1;

3     std::cout << 2;

4     std::cout << 3;

5 */

Here are some examples of bad line comments and good statement comments.

Bad comment:

1 // Set sight range to 0

2 sight = 0;

Reason: We already can see that sight is being set to 0 by looking at the statement

Good comment:

// The player just drank a potion of blindness and can not see
1
anything
2
sight = 0;

Reason: Now we know why the player’s sight is being set to 0

Bad comment:

1 // Calculate the cost of the items

2 cost = quantity * 2 * storePrice;

Reason: We can see that this is a cost calculation, but why is quantity multiplied by 2?
Good comment:

// We need to multiply quantity by 2 here because they are bought in


1
pairs
2
cost = quantity * 2 * storePrice;

Reason: Now we know why this formula makes sense.

Programmers often have to make a tough decision between solving a problem one way, or solving it another
way. Comments are a great way to remind yourself (or tell somebody else) the reason you made one decision
instead of another.

Good comments:

// We decided to use a linked list instead of an array


1
because
2
// arrays do insertion too slowly.

// We're going to use Newton's method to find the root of a number


1
because
2
// there is no deterministic way to solve these equations.

Finally, comments should be written in a way that makes sense to someone who has no idea what the code
does. It is often the case that a programmer will say “It’s obvious what this does! There’s no way I’ll forget
about this”. Guess what? It’s not obvious, and you will be amazed how quickly you forget. :) You (or
someone else) will thank you later for writing down the what, how, and why of your code in human
language. Reading individual lines of code is easy. Understanding what goal they are meant to accomplish is
not.

Variables in C++
Just like Javascript, C++ has the notion of variables. Declaring and using variables is a bit different from
Javascript though and in this lecture we will learn exactly how variables work in C++.
Read this article (http://www.learncpp.com/cpp-tutorial/13-a-first-
look-at-variables-initialization-and-assignment/).
int x; // define a variable named x, of type
1
int

At compile time, when the compiler sees this statement, it makes a note to itself that we are defining a
variable, giving it the name x, and that it is of type int (more on types in a moment). From that point forward
(with some limitations that we’ll talk about in a future lesson), whenever the compiler sees the identifier x, it
will know that we’re referencing this variable.
Value initialization and zero initialization
When a variable is initialized with empty braces, value initialization takes place. In most cases, value
initialization will initialize the variable to zero (or empty, if that’s more appropriate for a given type). In such
cases where zeroing occurs, this is called zero initialization.

int width {}; // zero initialization to value


1
0

Q: When should I initialize with { 0 } vs {}?

Use an explicit initialization value if you’re actually using that value.

int x { 0 }; // explicit initialization to value


1
0
2
std::cout << x; // we're using that zero value

Use value initialization if the value is temporary and will be replaced.

int x {}; // value initialization


1
std::cin >> x; // we're immediately replacing that
2
value

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es20-always-initialize-
an-object

Think about the following questions while reading:

1. What is a variable in C++?


Is an "object" with an identifier (name) and a content of a certain type. An object is a region of
storage (usually memory) that has a value and other associated properties. Generally speaking you can
imagine a box with a label (name) and some content (pens for example)

2. What is Definition of a variable?


You define a variable name (identifier) and type with a TYPE Identifier syntax
Here’s an example of defining a variable named x:
int x; // define a variable named x, of type
1
int

3. What is Instantiation of a variable?


Do you mean initialization of a variable? In this sense it means assign a value to the variable.
4. What is the difference between an l-value and an r-value?
l_val = r_val
In this expression r_val is assigned to l_val. 
5. What is an uninitialized variable and what kind of behaviour can you expect from such a variable?
It's a var to which has not been assigned a value, so it's value it's not known. You can have undefined
behaviour.
6. What is undefined behaviour?
Since you can't tell the value of an uninitialized variable, the program can have a undefined
behaviour.

At the bottom of the article you’ll see a quiz – make sure to do the
quiz!

Post your answers and feel free to discuss the quiz in this thread
(https://forum.ivanontech.com/t/variables-in-c-reading-assignment/
3160).

Functions in C++
Let’s move on and learn about functions!

Read this article (http://www.learncpp.com/cpp-tutorial/14-a-first-


look-at-functions/).
Think about the following questions while reading:

1. What is a function?
2. What function is run first of all in a C++ program?
3. What are return values?
4. Are nested functions allowed in C++?
At the bottom of the article you’ll see a quiz – make sure to do the
quiz!

Post your answers and feel free to discuss the quiz in this thread
(https://forum.ivanontech.com/t/functions-in-c-reading-assignment/
3161).
1. What is a function?
A piece of code with a name (you can call that function by that name() ) a return values, and some
parameters
2. What function is run first of all in a C++ program?
main
3. What are return values?
A function can return values, like a int , string, etc. Eventually it can return nothing (void)
4. Are nested functions allowed in C++?
No

Functions and Parameters in C++


Let’s move on and learn about functions!

Read this article (http://www.learncpp.com/cpp-tutorial/1-4a-a-first-


look-at-function-parameters/).
Think about the following questions while reading:

1. What is a function parameter?


2. Why do functions need parameters?

At the bottom of the article you’ll see a quiz – make sure to do the
quiz!

Post your answers and feel free to discuss the quiz in this thread
(https://forum.ivanontech.com/t/functions-and-parameters-c-
reading-assignment/3162).

1. What is a function parameter?


It’s a parameter you can pass to the function
2. Why do functions need parameters?
So that functions can “react” (elaborate ) to the parameters values.
Arrays in C++

Read this article (http://www.learncpp.com/cpp-tutorial/61-arrays-


part-i/).
Think about the following questions while reading:

1. What is an array?
2. Which index would you use to access the 2nd variable in an array?
3. What can you say about the size of an array?

Read this article (http://www.learncpp.com/cpp-tutorial/62-arrays-


part-ii/).
Think about the following questions while reading:

1. How can you initialize an array?


2. How can you get the size of an array in bytes?
3. How can you use the function sizeof in order to calculate the number of elements in an array?
4. What happens when you try to write outside the bounds of the array?

Btw, you may have heard about the EOS Vulnerability, it occured due to writing outside of the array
bounds (watch here: https://www.youtube.com/watch?v=37H1PJMoN3M).

At the bottom of the article you’ll see a quiz – make sure to do the
quiz!

Post your answers and feel free to discuss the quiz in this thread
(https://forum.ivanontech.com/t/arrays-in-c-reading-assignment/316
4).
1.   What is an array?
   An array is a struct that holds many vars with the same type and identified by an index
2.   Which index would you use to access the 2nd variable in an array?
  1
3.   What can you say about the size of an array?
   It has to be stated when you declare the array and the size has to be known at compile time.

1. How can you initialize an array?

int arr[10] {}; // all zeros


int arr[3] = { 10,20,30 };
1. How can you get the size of an array in bytes?

size(array)

3. How can you use the function sizeof in order to calculate the number of elements in an array?
   sizeof(array) / sizeof(array[0])

4. What happens when you try to write outside the bounds of the array?
   You write on stack (memory space). "stack smashing detected". Dangerous

Loops in C++
Let’s move on and learn about loops!

Read this article (http://www.learncpp.com/cpp-tutorial/55-while-


statements/).
Think about the following questions while reading:

1. What can we do with the while statement?


2. What value needs the statement  in the brackets evaluate to in order for the loop to continue?
3. What is an infinite loop?
4. What is an iteration?

At the bottom of the article you’ll see a quiz – make sure to do the
quiz!

Read this article (http://www.learncpp.com/cpp-tutorial/57-for-


statements/).
Think about the following questions while reading:

1. When is it a good idea to use a for statement (do a for loop) instead of the while loop  we learned
previously?
2. How would you write a for-loop in code?
3. What is an off-by-one error?

Post your answers and feel free to discuss the quizes in this thread
(https://forum.ivanontech.com/t/loops-in-c-reading-assignment/3168
).
1. What can we do with the while statement?
Make a loop based on a condition
2. What value needs the statement  in the brackets evaluate to in order for the loop to continue?
true
3. What is an infinite loop?
A loop that keeps iterating cause the condition is always true. 
while (true) {.....}
4. What is an iteration?
Repetition of a bunch of instruction

1. When is it a good idea to use a for statement (do a for loop) instead of the while loop  we learned
previously?
When there is an obvious loop variable 
2. How would you write a for-loop in code?
for (signed int i {0}; i<10; ++i) { do something }
3. What is an off-by-one error?
It happens when you do a mistake with the condition in the for loop.
Like
for (int i {0}; i<=10; ++i) {}
This will loop 11 times: did you mean 10?

#include <iostream>
#include <string>

using namespace std;

/*
  GUESS THE NUMBER
  1) Player 1 choose a number
  2) Player 2 try to guess the number
  3) Player 1 will tell if the guessed number is lower or higher or right!
*/

// welcome banner
void banner() {
  cout << 
    "GUESS THE NUMBER" << "\n\n"
    "1) Player 1 (played by computer) choose a number" << "\n"
    "2) Player 2 try to guess the number" << "\n"
    "3) Player 1 will tell if the guessed number is lower or higher or right!"  << "\n"
    << "\n";
}

// Get a random number


signed int getRandom() {
  return 10;
}

signed int question() {


  signed int num {};
  cout << "Guess the number: ";
  cin >> num;
  return(num);

int main() {
  // number of guessing attempts
  signed int moves {0};

  // Get the random number


  signed int secret {getRandom()};

  // guess flag
  bool guessed {false};

  // games log
  struct Games {
    signed int moves;
    signed int guess;
    string msg;
  };

  // Next time do it with variable size arrays


  Games gameLog[10000] {};

  // Welcome
  banner();

  // Starting the game


  while (!guessed) {
    signed int guess {};
    guess = question();
    moves++;
    // Check the guess number over secret
    if (guess == secret) {
      gameLog[moves-1] = { moves, guess, "You found it!"};
      cout << "You found it!" << "\n";
      guessed = true;
    } else if (guess < secret) {
      gameLog[moves-1] = { moves, guess, "Too low"};
      cout << "Too low" << "\n";
    // if (guess > secret)
    } else {
      gameLog[moves-1] = { moves, guess, "Too high"};
      cout << "Too high" << "\n";
  }
 }

  // Print game log


  cout << "\n\n"; 
  for (signed int i; i<moves; i++) {
    cout 
      << "#"
      << gameLog[i].moves 
      << " guess= "
      << gameLog[i].guess 
      << "  "
      << gameLog[i].msg 
      << "\n";
 }
}

Structs in C++
Let’s move on and learn about functions!

Read this article (http://www.learncpp.com/cpp-tutorial/47-structs/).


Think about the following questions while reading:

1. Why do we need structs?


2. What are members in a struct?
3. How do you access a member inside a struct?
4. What is a nested struct?

At the bottom of the article you’ll see a quiz – make sure to do the
quiz!

Post your answers and feel free to discuss the quiz in this thread
(https://forum.ivanontech.com/t/structs-c-reading-assignments/3169)
.
• Why do we need structs?
A struct (short for structure) allows us to group variables of mixed data types together into a single
unit
• What are members in a struct?
These variables that are part of the struct are called members (or fields)
• How do you access a member inside a struct?
In order to access the individual members, we use the member selection operator (which is a period)

struct Employee
{
int id{};
int age{};
double wage{};
};
Employee joe; // create an Employee struct for Joe
joe.id = 14; // assign a value to member id within struct joe
joe.age = 32; // assign a value to member age within struct joe
joe.wage = 24.15; // assign a value to member wage within struct joe

• What is a nested struct?


Structs can contain other structs. For example:

struct Employee
{
int id{};
int age{};
double wage{};
};

struct Company
{
Employee CEO{}; // Employee is a struct within the Company struct
int numberOfEmployees{};
};

Company myCompany;

Classes in C++
Let’s move on and learn about classes!

Read this article (http://www.learncpp.com/cpp-tutorial/82-classes-


and-class-members/).
Think about the following questions while reading:

1. Why do we need classes, why can’t we just use structs?


2. What are methods?
3. How would you define a class?
4. What is an object?

At the bottom of the article you’ll see a quiz – make sure to do the
quiz!

Post your answers and feel free to discuss the quiz in this thread
(https://forum.ivanontech.com/t/classes-in-c-reading-assignment/317
0).
1. Why do we need classes, why can’t we just use structs?
For convention structs are for data, classes are for data and functions.
2. What are methods?
Methods are the function in a class
3. How would you define a class?
With the key word class (it is similar to struct).
Like so:
class Ball {
public:
  double size;
  string color;
  void print() {
    std::cout << "ball info: " << "\n" ;
    std::cout << "  size: " << size << "\n";
    std::cout << "  color: " << color << "\n";
  };
}
4. What is an object?
An object is an instance of a class

Inheritance in C++
Let’s move on and learn about inheritance!

Read this article (http://www.learncpp.com/cpp-tutorial/111-


introduction-to-inheritance/).
Think about the following questions while reading:

1. Why do we need inheritance in C++?


2. Give a simple example of objects in the real world that could be modelled in C++ using
inheritance.

Read this article (http://www.learncpp.com/cpp-tutorial/112-basic-


inheritance-in-c/).
Think about the following questions while reading:

1. What is a superclass and what is a subclass?


2. How would you write a public inheritance in C++?
3. In what ways can a subclass extend the functionality of a superclass?

Post your answers and feel free to discuss the quiz in this thread
(https://forum.ivanontech.com/t/inheritance-in-c-reading-
assignment/3172).
1. Why do we need inheritance in C++?
Inheritance allow us to create objects that directly inherits properties of another objects. And so, we don’t
have to redefine some properties in our derived class.
2. Give a simple example of objects in the real world that could be modelled in C++ using inheritance.
A vehicle can be the base class for a car a truck etc…

1. What is a superclass and what is a subclass?


A superclass is the class you are inheriting from and a subclass is the class that inhertits from the superclass.
In the previous example vehicle is the superclass and car and truck are the subclasses
2. How would you write a public inheritance in C++?

// class ClassName: public SuperClassName


class Car: public Vehicle

3. In what ways can a subclass extend the functionality of a superclass?


It adds properties and methods specific to the subclass. For example a Vehicle superclass have generic info
about a vehicle like number of wheels and Truck subclass might have info about the payload

In a class you can have public, private, protected


public: are accessible from anywhere (in or out the classes)
private: are accessible only in the defined class
protected: are accessible also in the inherited classes

Very insightful lecture on data structures, if you’re interested and


want deeper understanding – watch it!
https://www.youtube.com/watch?v=eZQBx8YJ6Zs

typedef in C++
typedef double height;

height will be an alias for double

Template Functions
Template function give flexibility about the type of parameters and return value of a function. In this
example multiply can be used for int and double.

#include <iostream>

using namespace std;


template <class T>
T multiply(T a, T b) {
  return a*b;
}

int main() {
  cout << multiply(10,2) << '\n';
  cout << multiply(10.5,2.5) << '\n';
  //cout << multiply(10,2.5) << '\n'; // This doesn't work you cannot mix types (T can't be int and
double at the same time)
}

Template Classes & Typedef


We can use template also for classes. And use typedef to write a shorter and cleaner code.

#include <iostream>

using namespace std;

template <class T>


class MathTools {
  public:
    T mul (T a,T b) {
      return a*b;
  }
    T div (T a,T b) {
      return a/b;
  }
    T add (T a,T b) {
      return a+b;
  }
    T sub (T a,T b) {
      return a-b;
  }
};

typedef MathTools<int> IntTools;


typedef MathTools<double> DoubleTools;

int main() {
  // You can define intMathTools with explicit type or define a typedef for shorter and cleaner
code.
  //MathTools<int> intMathTools;
  IntTools intMathTools;
  //MathTools<double> doubleMathTools;
  DoubleTools doubleMathTools;

  cout << intMathTools.add(10,2) << '\n';


  cout << doubleMathTools.add(10.5,2) << '\n';
}

Value vs. Reference C


You can pass arguments to a function as value (it will be copied) or reference (it will interact with the actual
parameter not a copy. Use a '&' for reference)

#include <iostream>

using namespace std;

void incVal(int val) {


  val++;
  cout << val INSIDE incVal =  << val << endl;
}

void incReference(int& val) {


  val++;
  cout << val INSIDE incReference =  << val << endl;
}

int main() {
  int val {1};

  cout << val FIRST =  << val << endl;


  incVal(val);
  cout << val after incVal =  << val << endl;
  incReference(val);
  cout << val after incReference =  << val << endl;
}

OUTPUT:

val FIRST = 1
val INSIDE incVal = 2
val after incVal = 1
val INSIDE incReference = 2
val after incReference = 2
Pointers C++
Pointers are data type that holdes the address as his value. 
You can define a pointer using '*':  

int age { 51 };
// int* define a pointer (to a int)
// &var means the address of var
// ptr is a pointer to age (type int)
int* ptr {&age};
// (*ptr) means the int var that ptr points to
(*ptr)++; // 52

Test program:

#include <iostream>

using namespace std;

void printAge(int age) {


  cout << My age is  << age << n;
}

// int* 
void inc(int* val) {
  (*val)++;
}

int main() {
  int age { 51 };
  printAge(age);
  
  // &var means the address of var
  cout << The address of age is  << &age << n;

  // int* define a pointer (to a int)


  // ptr is a pointer to age (type int)
  int* ptr {&age};

  cout << The pointer is  << ptr << n;

  // (*ptr) means the int var that ptr points to


  (*ptr)++; // 52
  printAge(age);
  inc(ptr); // 53
  printAge(age);
  inc(&age); // 54
  printAge(age);

}
OUTPUT

My age is 51
The address of age is 0x7fffae64b2ec
The pointer is 0x7fffae64b2ec
My age is 52
My age is 53
My age is 54

Several Files in C++


When you have to work with several files you need to use header files that contains the class/function
prototypes.
See this to set up the proper environment:

https://dev.to/talhabalaj/setup-visual-studio-code-for-multi-file-c-projects-1jpi

Setting Up Project Directory


Having a manageable directory structure is important. It can help you quickly understand where you should
look for a file. I opted for the following structure because it is simple.

├── bin
├── include
└── src

The bin directory will contain the executable after compilation, the include directory will contain all the
header files, src will contain all the (as you have guessed) source files.

Setting up Makefile and adding C++ files


Now that we have a directory structure let's write the Makefile. Open VSCode in your project directory.
Before that, Let's see what is a Makefile.

Makefile is read by the make utility which executes the tasks defined in Makefile when the files are
modified. We will be using it to build our C++ code. You can learn more about Makefile and make here.

For our purposes, following Makefile should work well. so create a Makefile in the root of your project
directory. It should spell exactly the same with a capital M.

CXX := g++
CXX_FLAGS := -std=c++17 -ggdb

BIN := bin
SRC := src
INCLUDE := include

LIBRARIES :=
EXECUTABLE := main

all: $(BIN)/$(EXECUTABLE)

run: clean all


clear
./$(BIN)/$(EXECUTABLE)

$(BIN)/$(EXECUTABLE): $(SRC)/*.cpp
$(CXX) $(CXX_FLAGS) -I$(INCLUDE) $^ -o $@ $(LIBRARIES)

clean:
-rm $(BIN)/*

If you want to add additional libraries, you can add it after the LIBRARIES variable. You can also change
the name of the executable by changing the EXECUTABLE variable. You can tinker with CXX_FLAGS to
change the compiler's behavior (i.e. C++ version) but be sure you don't remove -ggdb flag or you won't be
able to debug the program correctly.

After creating the file, our directory structure should look like this:

├── bin
├── include
├── lib
├── Makefile
└── src

Now that we have our base ready let's add some C++ files. I will create a HelloWorld class that has
a say() function that will print out (you guessed it) "Hello, World". Let's create files in our project. I'm
gonna use the command line, you can use VSCode or your file manager.

$ touch include/HelloWorld.hpp src/HelloWorld.cpp src/main.cpp

Paste the following code in the respective files.

Add following to HelloWorld.hpp.

#include <iostream>

class HelloWorld {
public:
void say();
};

Add following to HelloWorld.cpp.

#include "HelloWorld.hpp"

void HelloWorld::say() {
std::cout << "Hello, World";
}
Add following to main.cpp.

#include "HelloWorld.hpp"

int main() {
HelloWorld world;
world.say();
return 0;
}

Testing our setup


Now, we have all our project all set up, we have added some test files. let's test everything out. Open a
terminal in the project directory and run make.

~/Documents/cpp_tut
▶ make
g++ -std=c++17 -ggdb -Iinclude src/HelloWorld.cpp src/main.cpp -o bin/main

Now, in the output, we will say the exact command that we would have run if we weren't
using make. make has got our back. We don't have to write the whole command each time.

Full explanation of this can be found here.

Optional: Lecture by Bjarne Stroustrup


(Creator of C++)
Meet the creator of C++
https://youtu.be/86xWVb4XIyE

You might also like