Intro to C++

Basic C++

C++ programs are written in ‘chunks’, and each chunk can be a function which contains some code, or a main chunk, which is the program that is run when the code is compiled. Here is an example of a main chunk that runs some code.

// include 'iostream' package
#include <iostream>          

// int means this will output an integer, main() signifies the primary code to run
int main()                               
{
  // pipe operator, using std library, cout is to output something, endl is to end line
  std::cout << "Hello" << std::endl;    
  
  // return integer 0 to show all is okay
  return 0;                             
}

This chunk of code will output the string Hello when run, with comments (starting with //) describing what each line does. However, this cannot be run by itself, since C++ is a compiled programming language; so we need a compiler. Firstly, we save this file as hello.cpp, and using the g++ compiler in the terminal will compile this code into an executable program.

g++ hello.cpp -o hello

This starts with g++, telling the terminal to use the g++ program, then chooses the file hello.cpp, -o hello specifies that the name of the output is hello. This has compiled a program into the current working directory which can also be run in the terminal.

./hello
## Hello

So the code has run succesfully! The only output was Hello as that was all that was specified to be output. Note that in C++ every integer, string, float, etc. needs to be defined in advance. Instead of in programming languages like R and Python, where nothing really needs to be specified in advance, variables need to be defined each time. For example,

int a = 3
float b = 14.512231
double c = 4e200
std::string d = "What up"

To further exemplify the usage of C++, consider the following example.

#include <iostream>
int main()
{
  for (int i=1; i<=100; i++)
  {
    if (i>=95)
    {
      std::cout << i << " ";
    }
    else if (i<5)
    {
      for(float j=-1.5; j>=-3.5; j--)
      {
        std::cout << i*j << " ";
      }
    }
  }
}

This has used a range of different code, including for loops and conditional statements if and else if. These are implemented in C++ similarly to the way they are implemented in R. In fact, the if statements almost have the exact same formatting as R. Loops are a bit different. The syntax that C++ uses for basic loops are for(initialise; condition; increment), where initialise refers to the first element that is being looped through, condition is the stopping condition of the loop and increment is how much the initaliser increases on each iteration.

In this case, for the increment we have used i++ and j--, which is shorthand for i = i + 1 and j = j - 1. The stopping conditions are when i is less than or equal to 100, and when j is greater than or equal to -3.5. Each iteration of the loop checks two conditions, the value of i, and different operations happen when i is less than 5, or greater than or equal to 95. We can run this code to see the output.

g++ loopif.cpp -o loopif
./loopif
## -1.5 -2.5 -3.5 -3 -5 -7 -4.5 -7.5 -10.5 -6 -10 -14 95 96 97 98 99 100

Times Table Example

Consider for a further example writing a function to print the times tables for a given number, a given number of times. For this, we can exemplify the use of multi-file programs. By creating a header file, with extension .h, and including this in our main program, we can specify functions in a different file. This helps navigate large code files, and separating different functions in different files can be extremely useful.

Let’s start by creating a times table function in a timestable.cpp file. This takes two integer inputs, the first being the times table we want to print, and the second being the maximum number we want to multiply to the first input.

#include <iostream>

void timestable(int a, int b)
{
  for(int i = 1 ; i <= b; i++)
  {
    std::cout << a*i << " ";
  }
  std::cout << std::endl;
}

So this loops from i=1 to b, and multiplies a by i on each iteration. Now we create a header file, called timestable.h, containing the following

#ifndef _TIMESTABLE_H
#define _TIMESTABLE_H

void timestable(int, int);
  
#endif 

This header file checks and defines the token _TIMESTABLE_H, and then simply declares the function timestable. When reading this function into another C++ file, it will declare the timestable function that is defined in timestable.cpp. A main file, called main.cpp to read the header file, which will define the timestable function, and run it for for two examples.

#include <iostream>
#include "timestable.h"

int main()
{
  std::cout << "Five times table" << std::endl;
  timestable(5, 10);

  std::cout << "Twelve times table" << std::endl;
  timestable(12, 12);
}

So we are expected the output of the five times table, up to 5 \(\times\) 10, and the twelve times table, up to 12 \(\times\) 12. Let’s compile and run this program.

g++ main.cpp timestable.cpp -o timestable
./timestable
## Five times table
## 5 10 15 20 25 30 35 40 45 50 
## Twelve times table
## 12 24 36 48 60 72 84 96 108 120

So it has worked as expected.

Next