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!