Lesson 9 – Vectors

In the previous lesson, we learnt about arrays. Arrays are containers that store data. In order to declare an array, you need to specify what type of data it stores, and the array cannot be used to store any other data types. You will also need to declare the size of the array. Once initiated, the array cannot change the number of data it stores.

In many situations, we would like to dynamically add or delete data from our array. Think of a contact list. You may want to add more contacts, or remove some that are no longer relevant. In such situations, you could use a modified kind of array to store the data. This data type is called a vector.

Declaring vector

To use a vector, you will need to include the <vector> in the preprocessor. vector is contained inside the C++ Standard Template Library (STL). You may need to use many STL data structures in writing complicated programs.

#include <vector>

Read the C++ documentation for vector.

The two very important methods of vector class is push_back() and pop_back(). push_back() adds a new data to the end of the vector while pop_back() removes the last data from the vector. at() allows you to access the data at the particular index.

std::vector<int> my_vector = {4, 6, 8};
std::cout << my_vector[1] << std::endl;

The output is 6 because it has in index of 1.

Challenge 1

Modify the program in Lesson 8 to use vector class. This allows you to store any number of records in your program.

Challenge 2

List all the natural numbers below 1000 that are multiples of 3 or 5. Store these numbers in a vector. Sum up all these numbers.

The correct answer is 233168.

Lesson 8 – Arrays

In this lesson, we shall learn a very important data structure that is very commonly used in programming. This data structure is called the array.

When you want to store many information that uses an index to keep track, an array is the data structure to use. Some examples are like storing telephone numbers, marks and grades.


Refer to the C++ documentation on array. There are a few ways to declare an array:

int foo[5]; // declare array with a storage of 5 elements
int foo[5] = {16, 2, 77, 40, 12071}; // declare array with 5 integers inside
int bar[5] = {10, 20, 30};
int baz[5] = {};
int foo[] = {16, 2, 77, 40, 12071}; // automatic resize of array to fit the elements

You can access an array element by using its index.

Using the example in the documentation:

// Program 8.1
#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
    for ( n=0 ; n<5 ; ++n )
        result += foo[n];
    cout << result;
    return 0;

Before you type the program, guess what this is going to do. After this, type and run the program. Did you get what was expected?

Characteristics of Arrays

Arrays are very powerful data structures that is widely used in programming. However beginners usually think that you can add elements whenever you want to. This is not the case. An array, once declared, cannot change its number of storage. In some modern programming languages, this limitation is removed such that the array can dynamically change its storage. However, C++ is not such a language.

In the next lesson, we shall discuss array’s more powerful cousin, the vector. For this lesson, let us use arrays to perform some useful operations.

Challenge 2

You are a teacher and you have 10 students. You want to keep all their test marks in an array and use it to calculate the average. Also print out the highest mark and lowest mark.

This challenge is equivalent to the IGCSE Computer Science syllabus requirement for programming.

Input: you will key in ten marks altogether.

Output: Console will print out the average, highest and lowest marks.


Lesson 7: Functions

Remember that a C++ program always start from the main function? In this lesson, you will learn about what a function is.

An add function

In the earlier, you learned to write a program to add two numbers.

//Program 7.1
int x = 0, y = 0;
int answer = 0;
std::cin >> x;
std::cin >> y;
answer = x + y;

Instead of adding the two numbers inside the main function, now I want to add them in a function. To do this, I need to declare a new function (computer doesn’t know about your new functions unless you declare them, like variables). The way to declare a function is this:

return_type function_name (data_type variable_name, ...)

For example, in the case of an add function, I would need to have two arguments so that I can add them. The two arguments will be declared inside the parenthesis. After adding, I need to return the answer to whatever variable that calls the function.

int add (int x, int y)

Above means that the add function takes in two inputs x and y of the integer type, and returns an integer type. Modify Program 7.1.

// Program 7.2
int add (int x, int y){ 
  return x + y; 

int main(int argc, const char * argv[]) {
 int x = 0, y = 0;
 int answer = 0;
 std::cin >> x;
 std::cin >> y;

 answer = add(x,y);
 std::cout << answer << std::endl;

 return 0;

You might ask why not just add the values inside the main function. If your program is large, having many operations inside your main function makes it unreadable. Breaking out the operations into functions make it easier for your program to be read and understand.

Other examples

A function may also return null type. This means that it does not return anything. To declare such type of functions, use the keyword void.

// Program 7.3
void sayHello () {
 std::cout << "Hello" << std::endl;

int main(int argc, const char * argv[]) {
 return 0;

In Program 7.3, you see that the sayHello function does not need any input, and it does not return any type. If a function does not need any arguments, then use a pair of parenthesis ().

Challenge 1

Write a program to add, subtract, multiply and divide two integers. Break out each operation into its respective functions. Ask user to select an operation using 1,2,3 or 4, representing add, subtract, multiply and divide respectively. Also ask user to input two integers.

Output the answer to console.

Challenge 2

A classic programming exercise is called the FizzBuzz Test. The problem is stated below:

“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”

Write a program that perform the above test.






Answers: Lesson 8

// Challenge 2

#include <iostream>

int main ()
 int marks[10];
 int total = 0, max = -1, min = 100;
 for (int i = 0; i < 10; i++) {
 std::cout << "Enter mark " ;
 std::cin >> marks[i];
 total += marks[i];
 if (max < marks[i]) {
 max = marks[i];
 if (min > marks[i]) {
 min = marks[i];
 std::cout << "The maximum mark is " << max << std::endl;
 std::cout << "The minimum mark is " << min << std::endl;
 std::cout << "The average mark is " << total/10.0 << std::endl;
 return 0;


Lesson 6: Revision to while

Revise lesson 5 and attempt Challenge 2 and 3 once more.

Intermediate while

while is powerful because it allows a program to run until a certain condition is reach. Remember that you wrote a program to find the first 10 Fibonacci numbers in Lesson 4?

Challenge 1

Now, rewrite you program to find the number of Fibonacci numbers that are less than 1000. You will need to use the while keyword. Hint: you need to use if to check whether the Fibonacci number is greater than 1000. If it is, stop the while loop.

Reading/writing from a file

The programs that you are able to write till now read values from keyboard and output to the console. Sometimes, you might want to read large amount of data and the data is usually presented in a file. In this section, you will learn how to read and write to files on the computer.


You include the iostream to read from keyboard and print to console. If you are going to read and write to file, then you need to include the filestream library.

#include <iostream>
#include <fstream>

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  return 0;

Go to this web page and read until you reach Text files.

Challenge 2

Lesson 5: while statement

In last lesson, we looked into using the if selection and for loop to make a program more dynamic. We also tried writing a program to print the first 10 Fibonacci numbers.

Challenge 1

Can you modify what you have written to print out a certain number of Fibonacci numbers according to the user input?

while statement

In this lesson, we will study another loop function. while loop is used when you do not know how many repetitions you are going to make. The general usage is

while (true) {
    //do the code block until condition is false

For example, you may want to continue adding scores until you run out of scores. Then you want to compute the average. Study the code below:

    int sum = 0, mark = 0;
    while (std::cin >> mark) {
        sum += mark;
    std::cout << sum << std::endl;
  1. Before you type in the code, what do you think this code does?
  2. How does the condition std::cin >> mark in the while statement work?

Now type this code and run it. How do you end the standard input? If you are on a Mac, press and hold Control-D. If you are using Windows, press and hold Control-Z.

Does the code do what you expect? Now, try stepping into the code line by line for three inputs, 5, 7, 3. What is the output?

Challenge 2

You can use the while statement to make a program runs until you quit. As an example, let us try to write a program to that accepts a name until the user decides to quit. When the user quit, the program will print out the number of names entered.

Tip: You need a counter variable to count the name number. Also, you may try to write the algorithm using pseudocode. In other words, write your solution in plain English using MS Word.

Challenge 3

Using a while statement, write a program to compute the factors of an integer.

Lesson 4: Strings, if and for statements

In last lesson, we covers std::string and basic logic using if. Let’s study the example below.

#include <iostream>
int main() {
    char gender = ''; // single quotes are for char, double quotes are for string.
    std::cin >> gender;
    if(gender = 'm') std::cout << "Hi Sir!";
    else std::cout << "Hi Ms!";

    return 0;

Before typing this into you IDE, suggest what it does. Now, type this code and run. Does it perform what you expect?

More std::string

Challenge 1

Refer to the C++ documentation for std::string. Now, you will write a program that test whether a string entered in cin is more than 10 characters or not. First, look for a method that can tell you the length of a string. If it is, then print “This word is too long.”. Otherwise, print “This word is within acceptable length.”.

Hint: You will need to read in a string and use logical if to decide whether the string is within acceptable length or not.

For loop

If you want to perform a fix number of repetitions, use a for loop. Study the code below and suggest what it does.

#include <iostream>
int main(int argc, const char * argv[]) {
    int sum = 0;

    for (int i = 0 ; i < 10 ; i++) {
        sum = sum + i;
    std::cout << sum;
    return 0;

Is the output the same as what you expect?


If you were expecting 55 but get a 45 from the console, you will need to debug what is wrong with the program. One way to do this is to trace the runtime step by step. To do this, we need to use the step functions of your IDE. For Xcode, you need to insert a breakpoint by clicking on the leftmost bar. Then use the step function below to run step by step.




You will be able to see the values of the variables changing as the program runs. Use this to find out why the sum is 45 and not 55. Then modify the program to make it sum to 55.

Challenge 2

Write a program to print the first 10 Fibonacci numbers. Fibonacci numbers are numbers that are sum of the previous 2 integers. For example,


If your code runs successfully, share it by copy and paste to the comment in this post.

Lesson 2: Variables

Variables are created in computer programs so that they can hold certain values. If we want to write a program to add two numbers, then we would need to have two variables to hold the numbers so that they can add up together. We shall discuss some of the types of variables are are available for you to use in a program.

Types of variables

The most common variable types that we shall use in our programs are:

  • int: integers only hold whole numbers. They have a small range.
  • longint: long integer are integers that have larger range.
  • double: these are numbers that have decimal places. Double type is able to store more digits.
  • char: characters are single letters, digits or symbols that are uniquely represented by an integer in the ASCII table.
  • string: strings stores anything within a pair of double quotes. You can use strings to store a sentence, a paragraph or a word. If you store a number as a string(within double quotes), this “number” will not be treated as a number. We shall look into the details below.

Declaring variables

A computer does not know anything unless the programmer tells it what to do. As a result, your computer program would not understand any variables that you create unless you explicitly instruct your program that you are creating those variables. We call this “variable declaration”.

We have studied some keywords from the previous class. std::cout is an example. The reason why your program understands what std::cout is is because you have the header line #include <iostream>. When you include that statement, you are giving your program a ready made list of important keywords that are used in input/output operations. Hence, your program understands what std::cout is.

//Program 2.1
#include <iostream>
int main {
  std::cout << "Hello world!";
  return 0;

You should be able to run this program successfully. Now, edit the program by removing the #include statement.

int main {
  std::cout << "Hello world!";
  return 0;

Your compiler will prompt an error message.

We shall now declare some variables.

//Program 2.2
#include <iostream>
int main {
  int x; // declare variable x as an int
  int y; // declare variable y as an int
  x = 1; // assigning value 1 to x
  y = 2; // assigning value 2 to y
  std::cout << x + y << std::endl;

  return 0;

You should get a number 3 in the console output. When you declare a variable, you are telling the computer to allocate a space in the memory to store the variable.  The space doe not contain any value, yet. By assigning values to the variables, you are storing the values in the space that has been reserved during the declaration.

Often, we would want to declare and assign the variables in one statement.

#include <iostream>
int main {
  int x = 1, y = 2;
  std::cout << x + y << std::endl;

  return 0;

Investigate variable types

Now that you are able to declare and assign values to variables, we shall look into the characteristics of different types of variables. From here onwards, I shall leave out the preprocessor(#include statement) and the main function’s declaration.

// Program 2.3
int x = 1, y = 2;
int z; //declares z without assigning any value
z = x + y;
std::cout << z << std::endl;
z = x - y; 
std::cout << z << std::endl;
z = x * y; // * is multiply
std::cout << z << std::endl;
z = x / y; // / is divide
std::cout << z << std::endl;
z = x % y; // % gets the remainder
std::cout << z << std::endl;

The output of Program 2.3 is



The interesting part  comes from the fourth output from the division operation. The reason why the output is 0 instead of 0.5 is because z is declared to be an integer, hence it will truncate any decimal digits. Now, modify Program 2.3 to declare z as a double.

double z;

After running, the compiler gives you the same result again. This is because both its operands are integers, hence the output will still be an integer. Now, declare x to be a double (both x and z are double). You will get an error in the last operation, the modulus % only works with integers. Since x is a double, the compiler complains this error.

Remove the modulus statement together with its std::cout statement and run. You will get 0.5 for the division operation. This lesson shows that you need to plan carefully what type of variable to be used when you write a program. Integers are generally used for counting and logic purposes. Unless you have very good reasons, use double variables to hold values.


char is a symbol that is represented internally by the computer following the ASCII code.

// Program 2.4
char x;
x = 35;
char y = 'c';
std::cout << x << std::endl;
std::cout << y << std::endl;

You get a # instead of 35. This is because x is declared as a char, hence it would be output as a char.


std::string is the type that holds multiple char between a pair of double quotes. When you declare string type, you need to prepend std:: because the string is a complex type that is defined in the std library. This is in comparison to the other native types like int, double and char.

// Program 2.5
std::string x = "This is a string. ";
std::string y = "This is another string.";
std::cout << x + y << std::endl;

In this example, you see that strings can be added together by appending one string to the other. It cannot work with other arithmetic operators however.

Getting input from user

You can declare a variable and then ask user to give it a value when the program is running. The keyword that do this is std::cin. Note that >> points to the right as compared to std::cout << which points to the left.

// Program 2.6
int x, y;
std::cin >> x; // any user input is assigned to the variable x
std::cin >> y;
std::cout << x + y std::endl;

When you run the program, your console output appears blank. It is actually waiting for you to enter a value. Try keying 5 and strike Enter. Key 3 and strike Enter. The number 8 appears.

Challenge 1

Write a program that accepts from user two inputs. Print out the value of adding, subtracting, multiplying and dividing the two numbers. Ensure that the program works correctly when the user enters either integers or doubles.

Lesson 1: Introduction

Read this post to understand what the objectives of this course is and also know what preparations are needed for this course. After you installed the IDE, you can proceed with this lesson.

A basic C++ program

Type the following code into your IDE. Ignore all the line labels e.g. 1:, 2:.

1:// Program 1.1
2:#include <iostream>
3:int main (int argc, const char * argv[]) {
4:  std::cout << "Hello World!" << std::endl;
5:  return 0;

Since this is your first program, we will spend a little time explaining all the statements.

Statement 1 starts with //. Two backslashes denote a comment. Anything after the two backslashes are ignored by the compiler till the end of the statement. End of statement is usually represented by “Enter” key strike.

Statement 2 is called the preprocessor. A computer does not know anything unless the programmer tell it what to do. Although the compiler contains some very basic functions that allow you to create variables (lesson 2), the more complicated functions such as printing to the console need to be defined in details. These details are located in the library iostream. io means input/output, and iostream handles all operations that involves input and output. In program 1.1, you want to output the statement “Hello World!” to the console. Hence, you need to call the iostream library using the preprocessor #include.

Statement 3 is the declaration of the main function. A C++ program always starts with the main function. Your program must have this statement. int argc, const char * argv[] is enclosed in the pair of parenthesis. This statement forms the arguments for the main function. Arguments are the inputs to a function. You will learn more about arguments in later lessons on functions. The argument is needed if you want to add inputs when you run the program in command line.

In statement 4, std::cout refers to the standard output. Generally, this means the console, which the the screen. Here, you will print the sentence “Hello World!” onto the screen. std::endl will cause the cursor to move to the next statement. It is a good practice to use it at the end of a std::cout statement. All statements must end with a semicolon ;.

Some functions return values. main function is one such function. Since main function was declared as int main(), it will return a value. Returning 0 means the program runs successfully.

The body of a function is enclosed in a pair of braces {}. Hence, you need to end the main function with the closing } in statement 6.

Compiling and running program

A computer only understands binary numbers 1 and 0. It is not going to understand the code that you typed in Program 1.1. In order to translate this code to machine language, you need to compile it.

In most IDE, compiling a program requires you to select the Build function from the menu bar. Locate Build in your IDE and click on it. After that, select and click Run. Some IDE compiles and run if you click Run while others run only the last compiled program. If you make changes and click Run, you might not get the result from the latest changes. Hence, it is a good practice to click Build follow by Run.


After running, you will get the output Hello World! on the screen. Notice that the cursor is on the next line.

Challenge 1

Write a C++ program that greets you. The output should be similar to

Good Day Stanley!