Skip to content

Basics of C++

File extension

We use .cpp for C++ source codes.

Execution

C++ is a compiled language, meaning that it will be translated into machine codes that can be understood directly by the system. Hence, in order to execute a C++ program, we need to compile then run the executable.

Let's use the Hello, World! program as an example.

hello-world.cpp
1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
    std::cout << "Hello, World!" << std::endl;

    return 0;
}

Simply we run

g++ hello-world.cpp

An executable with the default name a will be created.

On Windows, we should see a.exe. On macOS/Linux, we should see a.out.

We can also use the -o flag to specify the name of the executable.

g++ hello-world.cpp -o hello-world

In this case, the named executable will generate.

After all, we can run the executable and expect Hello, World! to be printed in the terminal.

Semicolons

Every C++ statement ends with a semicolon (;).

Variables

Variables are containers for values.

C++ is static typed, meaning that to create a variable, we have to specify the type so that we can assign value accordingly.

In C++, there are some basic types of variables:

  • int
  • float
  • double
  • char
  • string
  • bool
create-variables.cpp
#include <iostream>

using namespace std;

int main()
{
    int a;
    float b;
    double c;
    char d;
    string e;
    bool f;

    return 0;
}

When we create variables, we can use assignment operator = to initialize a value.

create-variables-with-values.cpp
#include <iostream>

using namespace std;

int main()
{
    int a = 128;
    float b = 0.1;
    double c = 0.3;
    char d = 'A';
    string e = "Hello, World!";
    bool f = true;

    return 0;
}

We can also create constants that cannot change their values.

modify-constant.cpp
1
2
3
4
5
6
7
int main()
{
    const int value = 1;
    value = 2;

    return 0;
}

Try to compile the codes above, an error shall raise 😢 :

.\modify-constant.cpp: In function 'int main()':
.\modify-constant.cpp:8:11: error: assignment of read-only variable 'value'
    8 |     value = 2;
      |     ~~~~~~^~~

Output

To display values in the terminal, we use cout together with << operator.

To display a newline character, use endl.

print-variables.cpp
#include <iostream>

using namespace std;

int main()
{
    int a = 128;
    float b = 0.1;
    double c = 0.3;
    char d = 'A';
    string e = "Hello, World!";
    bool f = true;

    cout << "a is " << a << endl;
    cout << "b is " << b << endl;
    cout << "c is " << c << endl;
    cout << "d is " << d << endl;
    cout << "e is " << e << endl;
    cout << "f is " << f << endl;

    return 0;
}

User Input

While cout is used to output, we use cin, together with >> operator, to capture user input.

input-x.cpp
#include <iostream>

using namespace std;

int main()
{
    int x;
    cout << "Value of x is ";
    cin >> x;
    cout << "x is " << x << endl;

    return 0;
}

Comments

In C++ we use // to comment out a single line, everything after // is ignored by the compiler.

We can use it in end of line

int x = 1; // x is 1

or from the beginning

// y is 2
int y = 2;

In case we need to provide a long piece of text as comment, use a pair of /* and */. Any text in-between will be ignored by the complier.

1
2
3
/* z is supposed to be 3
but ends up being 4 */
int z = 4;

Assignment 1

Write a C++ program named greeting.cpp to ask user for his/her name and display "Hello, name".

The workflow the program is as follows:

  1. The command line would prompt "What is your name? "
  2. Suppose we enter "Jack".
  3. The command line displays "Hello, Jack"
Sample Solution
greeting.cpp
#include <iostream>

using namespace std;

int main()
{
    string name;
    cout << "What is your name? ";
    cin >> name;
    cout << "Hello, " << name << endl;

    return 0;
}

Operators

Arithmetic Operators

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division
  • % for modulus
  • ++ for increment by 1
  • -- for decrement by 1

Assignment Operators

We use = to assign value to a variable, just like we mention earlier.

We can also chain = with the arithmetic operators to simply the code

For example,

int a = 1;
a = a + 2;

is equivalent to

int a = 1;
a += 2;

Comparison Operators

Comparison operators are used to compare two values. They always return a boolean (true/false).

compare.cpp
#include <iostream>

using namespace std;

int main()
{
    const int a = 1;
    const int b = 2;

    cout << (a > b) << endl;  // Greater than
    cout << (a < b) << endl;  // Less than
    cout << (a >= b) << endl; // No less than
    cout << (a <= b) << endl; // No greater than
    cout << (a == b) << endl; // Equal to
    cout << (a != b) << endl; // Not equal to

    return 0;
}

Logical Operators

Logical operators are used to determine the logic between variables or values

  • && for logical and
  • || for logical or
  • ! for logical not
logical.cpp
#include <iostream>

using namespace std;

int main()
{
    const int a = 1;
    const int b = 2;

    cout << ((a > b) && (a < b)) << endl;
    cout << ((a >= b) || (a <= b)) << endl;
    cout << !(a == b) << endl;

    return 0;
}

Assignment 2

Write a C++ program named circle.cpp that prompts for the diameter (cm) of a circle and computes and displays the circle's area and circumference.

We can assume π equals 3.14159.

Sample Solution
circle.cpp
#include <iostream>

using namespace std;

int main()
{
    double diameter;
    cout << "Enter Diameter: ";
    cin >> diameter;
    double pi = 3.14159;
    double radius = diameter / 2;
    double area = pi * radius * radius;
    double circumference = pi * diameter;
    cout << "Area = " << area << endl;
    cout << "Circumference = " << circumference << endl;

    return 0;
}

Assignment 3

Write a C++ program name triangle.cpp that prompts for the lengths of 3 sides of a triangle and displays the area of that triangle.

Check out Heron' formula if not sure about the math.

And we can find the square root function from <cmath>

Sample Solution
triangle.cpp
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    float a, b, c;
    cout << "Side a: ";
    cin >> a;
    cout << "Side b: ";
    cin >> b;
    cout << "Side c: ";
    cin >> c;
    float s, area;
    s = (a + b + c) / 2;
    area = sqrt(s * (s - a) * (s - b) * (s - c));
    cout << "Area is " << area;
}