Skip to content

2. Building Blocks

Writing Comments

Using comments, which are ignored by the compiler, in the source code is usually a good way of explaining the way of working of your code to other people and your future self. C++ gives two kinds of comment-styles. The first style is started by using //. This indicates that until the end of the line there is a comment which should be ignored by the compiler.

int main() {
    // we put a one-line comment here
}

The other style starts with /* and ends with */. So this style is not ended by any newline- or other special character.

int main() {
    /*  
        Here we can
        write our comment
        in more than one line!
    */
    std::cout /*We can even create a comment inside a statement!*/ << "Hello, World\n";
}

Explanation of the Streaming Operator

Before we go into the details of the C++ streaming operator << for cout, let us briefly discuss the mathematical addition \(+\) of two real numbers \(x\) and \(y\). The addition is a mathematical operation. A mathematical operation is nothing more than a function with a change of notation to make it more useful. The typical notation for the addition is given by the following expression.

\[ x+y \]

This formulation does not directly result from its definition. Looking at the typical definition for operations like \(+\), we get something like the following.

\[ +:\mathbb{R}\times\mathbb{R}\to\mathbb{R} \ ,\quad (a,b) \mapsto +(a,b) \]

This would mean that the expression \(x+y\) would have to be expressed as below.

\[ +(x,y) \]

For convenience, in mathematics one makes those expressions interchangeable by definition.

\[ +(x,y) = x+y \]

Hence, if we would like to add three real numbers \(x\), \(y\), and \(z\), we could write the following.

\[ x + y + z = (x+y)+z = +(x,y) + z = +(+(x,y),z) \]

In programming, the procedure used for the left-hand side is typically called chaining because we are able to chain all additions by only adding another \(+\) and a variable. The change of notation for mathematical operations, like \(+\), \(\times\), or \(\frac{\cdot}{\cdot}\), makes it easier to express a specific intention.

In C++, the concept of mathematical operations does exist as well. The functions of these mathematical operations are called operators and can be implemented by the programmer like any other function. But as before, to use them one has to change to the notation of mathematical operations. The operator << is a mathematical operation which takes a so-called output stream, like cout, as its first argument, and a variable to be printed to the output stream as the second argument. To enable the chaining mechanism as for the \(+\) operation, << always returns its first argument.

cout << x;           // <=>  <<(cout, x) = cout
cout << "x = " << x; // <=>  <<(<<(cout, "x = "), x) = cout

// <<(<<(<<(cout, "x = "), x), '\n') = cout  <=>
cout << "x = " << x << '\n';

Fibonacci Sequence

The Fibonacci sequence is a sequence \(f:\mathbb{N}\to\mathbb{N}\) of natural numbers such that for all \(n\in\mathbb{N}\) the following holds.

\[ f(1)=1 \ ,\qquad f(2)=1 \ ,\qquad f(n+2) = f(n+1) + f(n) \]

The first few elements of this sequence are shown below. It is used as a typical programming example.

\[ (f(n))_{n\in\mathbb{N}} = (1\,,\ 1\,,\ 2\,,\ 3\,,\ 5\,,\ 8\,,\ 13\,,\ 21\,,\ 34\,,\ 55\,,\ 89\,,\ \ldots) \]

Our goal is it to implement an algorithm which will generate a certain amount of those numbers and print it to the screen. For this, create a new folder in your course folder and open your text editor.

$ pwd
/home/lyrahgames/projects/cpp-course
$ mkdir 03-fibonacci
$ ls
01-hello  02-input  03-fibonacci
$ subl .

Go into the new folder and create a new main.cpp file.

$ cd 03-fibonacci
$ pwd
/home/lyrahgames/projects/cpp-course/03-fibonacci
$ touch main.cpp

For Loop

If we want to apply the computation rule for the Fibonacci sequence several times to be able to print more than a few values on the screen, we need a loop which is repeating parts of the code we have written. In C++, one typically uses the so-called for loop.

for (/* Initial Statement */; /* Loop Condition */; /* Iteration Statement */){
  /* Loop Block */
}
Before the for loop starts, the initial statement is executed. The for loop repeats the contents of its loop block as long as its loop condition is true. At the end of each loop block, it executes the iteration statement. A typical example is given below.

for (int i = 0; i < 10; ++i){
  cout << i << '\n';
}

Here, the initial statement is given by int i = 0. It defines a local variable i of type int which is only applicable in the block of the for loop, and initializes it with 0. The loop condition is given by i < 10. So as long as the variable i is smaller than 10 the loop block will be repeated. The iteration statement is given by ++i. After every loop block it makes sure to increment i by 1. In the loop block, we can use the locally defined variable i to print it for example.

Applying the for loop to the Fibonacci problem, we get something like the following.

#include <iostream>

using namespace std;

int main(){
  int f_1 = 1;
  int f_2 = 1;

  for (int i = 0; i < 10; ++i) {
    cout << "f(" << i + 1 << ") = " << f_1 << "\n";

    int f_tmp = f_1 + f_2;
    f_1 = f_2;
    f_2 = f_tmp;
  }
}

We have defined two starting values f_1 and f_2 as integers. Afterwards, we directly start with the loop and print the first argument on the screen. The actual computation of the Fibonacci sequence happens after the output.

int f_tmp = f_1 + f_2;
f_1 = f_2;
f_2 = f_tmp;

In the locally defined integer variable f_tmp, we store newly computed next Fibonacci element. At this point, we do no longer need the value of f_1. Hence, we will store the value of f_2 in f_1 to be able to store f_tmp in f_2. By computing the element \(f(n+2)\), we will therefore assume that the old value of \(f(n+1)\) is stored in f_2 and the value of \(f(n)\) is stored in f_1. For the next iteration, \(f(n+1)\) has to become \(f(n)\), \(f(n+2)\) has to become \(f(n+1)\), and \(f(n)\) is no longer needed.

Compilation with Custom Output Name

For compiling the code, this time, we will use a so-called flag to directly name the output executable. For g++, this can be done by writing -o and afterwards adding the name of your executable.

g++ -o fibonacci main.cpp

List the content of your folder and run your code.

$ pwd
/home/lyrahgames/projects/cpp-course/03-fibonacci
$ ls
main.cpp
$ g++ -o fibonacci main.cpp
$ ls
fibonacci*  main.cpp
$ ./fibonacci
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 3
f(5) = 5
f(6) = 8
f(7) = 13
f(8) = 21
f(9) = 34
f(10) = 55

Starting with Functions

void print_fibonacci(int n){...}
#include <iostream>

using namespace std;

void print_fibonacci(int n) {
  int f_1 = 1;
  int f_2 = 1;

  for (int i = 0; i < n; ++i) {
    cout << "f(" << i + 1 << ") = " << f_1 << "\n";

    int f_tmp = f_1 + f_2;
    f_1 = f_2;
    f_2 = f_tmp;
  }
}

int main() {
  print_fibonacci(10);
}
// Declaration:    Used for the interface.
void print_fibonacci(int n);

// Implementation: Used for the actual computation.
void print_fibonacci(int n){...}  
#include <iostream>

using namespace std;

void print_fibonacci(int n);

int main() {
  print_fibonacci(10);
}

void print_fibonacci(int n) {
  int f_1 = 1;
  int f_2 = 1;

  for (int i = 0; i < n; ++i) {
    cout << "f(" << i + 1 << ") = " << f_1 << "\n";

    int f_tmp = f_1 + f_2;
    f_1 = f_2;
    f_2 = f_tmp;
  }
}

Exercises

  1. Prompt the user of the program to input a number. Use this number as count of elements of the Fibonacci sequence to be printed on the terminal.
  2. Add a second and a third argument to print_fibonacci function to parameterize the starting values of f_1 and f_2. Test your implementation by calling the function in main several times with different argument values.

Last update: October 22, 2020