Computational Physics wiki (UCAM only) / C++ course homepage /

Simple C++ examples

What you want What it is called Examples
loops do .. while
loopswhile (has never-ending loop)
input from usercin
definition #define
pass by reference&
shared definitions#include (header file) and rand.h
conditional if / else
? (ternary operator)
switch / case
random random() (random integer between 0 and 231
srandom() (initialize/seed the generator) (seeds using time) (user-supplied seed)
input from command lineargv, sscanf
convert string to int or long intsscanf
integer arithmetic unsigned int
power (xy)pow(x,y)
bit-shift (1<<i)
Examine memory bit by bit& (bit mask)
input from fileifstream, open, getline, close
remember variablesstatic
arraysfloat vector[3]
char phone[11]
dynamically allocate memory for vectors/ arrays/ matricesint *a, new, delete
dynamically allocate double arrays/matricesdouble *a, new, delete
useful warnings when compilingmakefile Makefile
Classes class
convert between typescast, reinterpret_cast, static_cast (not yet finished)
The archetypical "Hello World" example program demonstrates output (printing) to the terminal. int main(), std::cout
Acquiring random integers. random()
Ensuring random numbers differ each time you run the program srand()
Getting random real in the range [0,1) random(), RAND_MAX
Example Monte Carlo calculation of Pi
Rounding error
Rounding error
Overflow error
Overflow error
Overflow error
Underflow error
Scope examples { and }
Program that tests if numbers are prime
A "monolithic" implementation of the "Three Map" map.
The 'evil' statement
Simple functions functions
Functions with arguments functions
Illustrate use (and misuse) of the stack. the stack
A better (more factorised) implementation of the "Three Map" map
An extension to the map program to allow multiple maps to be used function pointers
Crudly decompose functions using Fourier Transforms, and use these to do fractional derivatives.
Why arrays are confusing
Use arrays to rotate an image
Peer into memory
Do naughty things with pointers
Illustrate pointer usage
Play with sizeof sizeof
Find the Fourier Series of some simple functions, differentiate the Fourier Series a non-integer number of times. Use Gnuplot to show the result. sin cos gnuplot