## Introduction to

# C++

J. Reizenstein,

Y. Lifanov,

J. Mascie-Taylor,

Q. Caudron.

# Recap

Previously

- Arrays
- Functions
- Printing primes

# Arrays

Declaration and usage

    int nel = 10;
    int A[nel];

    for(int i = 0; i < nel; i++) {
      A[i] = i;
    }

    for(int i = 0; i < nel; i++) {
      std::cout << A[i] << "\n";
    }

# Functions

Declaration and usage

    #include <iostream>

    int square(int x) {
      return x*x;
    }

    int main() {
      for(int i = 0; i < 10; i++) {
        std::cout << square(i) << "\n";
      }
      return 0;
    }

# Solution

Naive prime test

    bool isprime(int x) {
      int y = 0.5*x;
      for(int i = 2; i <= y; i++) {
        if(x % i == 0) {
          return false;
        }
      }
      return true;
    }

# Solution

Printing 100 primes

    for(int i = 2, j = 0; j < 100; i++) {
      if(isprime(i)) {
        std::cout << i << "\n";
        j++;
      }
    }

# Warm Up

Printing checker pattern

1. Declare an integer n
2. Declare an n by n 2D array
3. To each element, assign a 0 or a 1
4. Value must depend on the index of element
5. Print the array
6. Example output for n = 4 :

    0 1 0 1
    1 0 1 0
    0 1 0 1
    1 0 1 0

# Hint

Use nested loops

    int A[n][n]; //declare n by n array
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        A[i][j] = /* some combo of i and j */;
      }
    }

You might also find this useful:

    int is_even = x % 2; //always a 0 or a 1 for x >= 0

# Solution

    /* creating pattern */
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        check[i][j] = (i + j % 2) % 2;
      }
    }
    /* printing */
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        std::cout << check[i][j] << " ";
      }
      std::cout << "\n";
    }

# File I/O

Using file streams

# File I/O

Basic writing

    #include <fstream> //required header
    int main() {
      std::ofstream ofile("myfile.txt");
      ofile << "Hello, world!\n";
      ofile.close();
      return 0;
    }

# File I/O

Works like std::cout

    std::ofstream ofile("myfile.txt");
    int x = 4 + 5;
    ofile << x << "\n";
    ofile.close();

# File I/O

Basic reading

    std::ifstream ifile("myfile.txt");
    int x;
    ifile >> x;
    ifile.close();

Works like std::cin

# Exercise

1. Print your checker pattern to file
2. Visualise the pattern in MatLab using:

    chk = importdata('file.txt');
    imshow(chk, 'InitialMagnification',1e5),

# Solution

Change the priting portion

    std::ofstream file("file.txt");
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        file << check[i][j] << " ";
      }
      file << "\n";
    }
    file.close();

Don't forget to

    #include <fstream>

# C++11

A newer standard

- Code::Blocks:
  1. Project -> Build Options -> Compiler Flags
  2. ... follow the C++11 ISO language standard
- G++ :

    g++-4.8 main.cpp -std=c++11

# Arguments

Input via console

# Arguments

Main function

    int main(int argc, char** argv) {
      /* some code */
      return 0;
    }

- argc - argument count
- argv - argument values

# Arguments

Providing values via console

    myexe.exe 0.1 2 yes

argv will look like:

    char argv[][256] = {
        {"myexe.exe\0"},
        {"0.1\0"},
        {"2\0"},
        {"yes\0"}
    };

# Arguments

Code::Blocks

1. Project -> Set program's arguments
2. Type in space delimited arguments

    0.1 2 yes

argv will look like:

    char argv[][256] = {
        {"myproj.exe\0"},
        {"0.1\0"},
        {"2\0"},
        {"yes\0"}
    };

# Arguments

Converting to values (before C++11)

    myexe.exe 0.1 2

    #include <cstdlib>
    int main(int argc, char** argv) {
      double  arg1 = atof(argv[1]);
      int     arg2 = atoi(argv[2]);
      return 0;
    }

# Arguments

Converting to values (since C++11)

    myexe.exe 0.1 2

    #include <string>
    int main(int argc, char** argv) {
      double  arg1 = std::stod(argv[1]);
      int     arg2 = std::stoi(argv[2]);
      return 0;
    }

# Exercise

Changing checkerboard size

1. Read cherboard size n from console
2. Try your code for different n
3. Note that you only have to compile once

# Solution

Change declaration of n

    #include <string>
    #include <fstream>
    int main(int argc, char** argv) {
      const int n = std::stoi(argv[1]);
      /* generate pattern */
      /* print array to file */
      return 0;
    }

# Random

The C++11 library

# Random

Before C++11

    #include <cstdlib>
    #include <iostream>
    #include <ctime>
    int main() {
      std::srand(std::time(0)); //seed with time
      int random_variable = std::rand();
      std::cout << "Random value on [0 "
                << RAND_MAX << "]: "
                << random_variable << '\n';
      return 0;
    }

# Random

Seeding PRNG

    #include <random> //c++11 and above only
    #include <ctime> //time
    int main() {
      int seed = std::time(0);
      std::mt19937 mt(seed); //random "engine"
      /* more code */
      return 0;
    }

# Random

Generating real PRNs

    std::mt19937 mt(seed);
    std::uniform_real_distribution<double> ur01(0, 1);
    double rnd = ur01(mt); //uniform on [0, 1)

# Random

Generating integer PRNs

    std::mt19937 mt(seed);
    std::uniform_int_distribution<int> ui05(0, 5);
    double rnd = ui05(mt); //uniform on [0, 5]

# Random

Non-deterministic RNs

    std::random_device rd;

Works in GCC, VS but not MinGW

# Random

Better seeding

    std::random_device rd;
    std::mt19937 mt(rd());

# Exercise

1. Create a uniform real distribution
2. Set the lower and upper limits to 0 and 1
3. Print out 10 random numbers
4. Run your code several times

Does the sequence repeat?

# Solution

    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> U(0.0, 1.0);
    for(int i = 0; i < 10; i++) {
      std::cout << U(mt) << "\n";
    }

# Exercise

1. Compute means of 105 sets of 103 RNs
2. Output all the means to a file

# Solution

    std::ofstream file("file.txt");
    for(int i = 0; i < n_sets; i++) {
      double sum = 0.0;
      for(int j = 0; j < n_smps; j++) {
        sum += U(mt);
      }
      file << sum/n_smps << ", ";
    }
    file.close();

# Exercise

Using MatLab

1. Load the means with importdata()
2. Use histc() to obtain the histogram
3. Normalise the histogram to obtain the PDF
4. Plot the PDF using:

    semilogy(x, pdf, 'o'),

$$\text{PDF} = \frac{\text{histogram}}{\text{bin width}\times\sum\text{histogram}}$$

# Solution

    x = importdata('file.txt'); %load data
    bins = linspace(.3, .6, 1000); %evenly spaced bins
    h = histc(x, bins);
    pdf = h/(sum(h)*(bins(2) - bins(1)));
    semilogy(bins, pdf, 'o'), %plot
    hold all, %keep current figure active

# Exercise

Compare to normal PDF

1. Compute the values of normal PDF:

    pdf = normpdf(bins, mu, sigma);

2. Plot the normal PDF as a solid line with

$$\mu = \frac{b - a}{2},\quad \sigma = \frac{1}{\sqrt{12n}}$$

# Solution

    n = 1e3; %number of samples
    mn = .5; %theoretical mean
    sd = 1/sqrt(12*n); %theoretical sigma
    pdf = normpdf(bins, mn, sd);
    semilogy(bins, pdf, '-'),

# Plotting tricks

Making prettier plots in matlab

# Line style

- Data as points
- Theory as lines

    errorbar(x, y, CI, 'ob', ...
        'MarkerFaceColor', 'b'), %blue circles
    hold on,
    h = ezplot('x^2', [-1, 1]);
    set(h, 'LineWidth', 2, ... %dotted red line
      'LineStyle', '--', 'color', 'r'),

# Axes

Changing limits and adding labels

    axis tight,
    axis square,
    xlabel('x'),
    ylabel('y'),
    title('Data vs theory'),

# Legend

Labelling lines

    legend('Data', 'Theory', ...
        'location', 'NorthEastOutside'),
    legend boxoff,

# Font

Default is too small

    set(gca, 'FontSize', 17),

# Example

Before and after

# Closing remarks

- Many universities give public access to their C/C++ courses (e.g. CAMBRIDGE)
- There is a 2nd year Physics C programming course at Warwick (PX270)
- For books, see THIS stackoverflow thread
- Their top rated beginner's book is available for free HERE
- Beware, programming books are often aimed at computer scientists. So they may not have many Physics examples
- Codecademy is a free online interactive coding tutorial. Have a go at learning Python HERE
- If you are looking for a challenge, check out PROJECT EULER

# The End