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!

Introduction to C++ Programming

In this course, we are going to use C++ for competitive programming. The goal for this course is to participate in the University of Waterloo’s Canadian Computing Competition in Feb 2016.

There are two levels of competition. If since all of you have little programming experience, we can only aim for the Junior Level competition. However, do not under-rate this Junior Level competition as some of the questions can be tricky too.

What software should I install?

C++ is a cross platform programming language. There are various tools available to do C++ programming on both Windows and the Mac platform. For Windows users, Visual Studio 2015 Community Edition is a very powerful Integrated Development Platform(IDE). This is the preferred development environment for our course for Windows users. Please check the C++ option when installing, as the default installation only installs C#. However, this software is large, and it is not possible for you to download and install in School (we are in Indonesia). If you are not able to install VS2015 in time for the training, then please install this light weight C++ IDE Dev-C++. It’s only 50MB.

For Mac users, the ideal IDE for C++ development is Xcode. This IDE is also huge, and you need to install prior to attending the training.

If you really can’t install anything in time for the training, then you can still use online compilers such as IDEOne. However, this is only a stop gap solution. Please install proper software once you have the chance.