Department of Engineering

1B C++ Computing

C++

1B CUED C++ crib

Here's a "cheat sheet" showing how to use some C++ features. I suggest you build up your own collection of reusable code.

Variables

// Some examples of creating and setting variables
int i;
int i=5;
int i,j;
int i=5,j;
unsigned int i;
const int j=99;
float f;
double g=99.9;
string s="hello"; // needs #include <string>
char c='h';
bool b=true;

Arrays

int month[12]; // An array of 12 integers. month[0] ...  month[11]

float grid[3][3]; // A 3 by 3 grid of real numbers

Decisions

// if
if (i==3) {
  // do this if i is 3
}

// if ... else
if  (i==3) {
   // do this if i is 3
}
else {
   // do this if i isn't 3 
}

// Boolean logic
if (3<num and num<5) {
   // do this if num is between 3 and 5
}

if (num1!=0 or num2>=5) {
   // do this if num1 isn't 0 or num2 is greater than or equal to 5
}

switch

switch (i) {
    case 0: cout << "i is zero" ;
            break;
    case 1: cout << "i is one" ;
            break;
    case 2: cout << "i is two" ;
            break;
    default: cout << "i isn't 0, 1, or 2";
            break;
    }

Loops

// while loop
int num=1;
while (num<11) {
   cout << num  << endl;
   num=num+1;
}

// for loop
for(int num=1;num<11; num=num+1) {
  cout << num  << endl;
}

// continue  and  break 
int num=1;
while (num<11) {
   num=num+1;
   if (num == 5)
      continue; // start the next cycle 
   if (num == 9)
      break;    // break out of the loop
   cout << num  << endl;
}

Input from keyboard

int num;
cin >> num;  

Output to screen

cout << i;
cout << "hello!";
cout << endl; // start a new line

cout << i << "hello!" << endl;

Program structure

#include <iostream> // We want to use input/output functions
#include <string>   // We want to use strings
using namespace std;      // We want to use the standard versions of
                          // the above functions.

// This is the main function
int main() {
   int i=3; // Create an integer variable and set it to 3
    // print the value of i and end the line 
   cout << "i has the value " << i  << endl;
}

Functions

// Prototype of a function called 'fun' that has no inputs or outputs
void fun();

// Prototype of a function called 'fun' that needs
// 2 inputs (an integer and a real) and produces an integer as output
int fun(int x, float y);
// The following complete program shows the prototype, call and code of a function
int double_i(int x);      // prototype 

int main() {
   int i= double_i(8);    // function call
}

int double_i(int x) {     // function code
    return x*2;
}

If you want a C++ function to modify an argument, pass it by reference (add '&' to the argument type):

   void value_func(int param) { param += 2; }
   void ref_func(int& param) { param += 2; }
   int main() {
      int x = 2;
      value_func(x); // x is still 2
      ref_func(x);   // x is now 4
   }

Files

#include <fstream>

// Reading
string message;
ifstream fin; // a variable used for storing info about a file
fin.open("secretmessage"); // trying to open the file for reading
if(fin.good()) {
      // we've managed to open the file. Now we'll read a line 
      // from the file into the string 
      getline(fin, message);
      // If num is of type int, read an integer from the file
      fin >> num;   
}


// Writing
ofstream fout;  // create a variable to store info about a file
fout.open("myData"); // try to open the file for writing
if(fout.good()) {
  fout << x << endl;   //write the contexts of variable x to the file
}
 

Operators

Here's a complete list. You'll never use many of these operators. The Associativity column indicates (for example) whether 8/4/2 is evaluated as (8/4)/2 (left to right associativity, resulting in 1) or 8/(4/2) (resulting in 4). Each row is a level of precedence, the highest first.

Associativity  Operator
left to right ::
left to right () [], ->, ., typeid, casts,
right to left ! (negation), ~ (bit-not)) new, delete ++, --, - (unary) , * (unary), & (unary), sizeof
right to left (type)
left to right *, /, % (modulus)
left to right -, +
left to right <<, >>
left to right <, <=, >, >=
left to right ==, !=
left to right & (bit-and), | (bit-or)
left to right ^ (bit-xor)
left to right &&, and
left to right ||, or
right to left ?:
right to left =, +=, -=, /=, %=, >>=, <<=, &=
left to right throw
left to right ,

Maths

#include <cmath>
using namespace std;    

float x,y;

sqrt(x);
pow(x,y); // x to the power y;
sin(x);   // radians
cos(x);   // radians
tan(x);   // radians
exp(x);   // exponential
log(x);   // natural log
log10(x); // base 10 log
fabs(x);  // absolute value
ceil(x);  // round up 
floor(x); // round down
#include <cstdlib>

using namespace std;    

srandom(time(0)); // intialize randomiser
random();         // random integer

Classes

// Create and use a new class
class Cat {
public:
   string name;
   float weight;
};

Cat c;

c.name="kitty";

Vectors

To declare a vector that can contain elements of type double use

   #include <vector>
   ...
   using namespace std;

   vector<double> v;

The type of element that the vector holds is written between the angle brackets. The vector declared above is initially empty. You can...

  • get the number of elements in the vector with the size() member function:
       cout << v.size() << endl;
    
  • append an element onto the back of the vector using the push_back(...) member function:
    
       v.push_back(3.14); // increases v.size() by 1
       v.push_back(2.71); // increases v.size() by 1
    
  • access the elements of the vector using '[]' (the index of first element is 0):
       cout << v[0] << endl;
       v[1] = 1.68;
    
  • declare a vector with a known size:
       vector<int> some_ints(10);  // 10 int elements, uninitialized
    
  • specify a default value in the declaration:
    
       vector<double> some_reals(10, 0.0);  // 10 real numbers, all zero
    
  • loop through the vector forwards...
       for (unsigned int i=0; i<v.size(); ++i) {
         cout << v[i] << " ";
      }
    
    
  • ...or backwards:
       for (int i=v.size()-1; i>=0; --i) {
         cout << v[i] << " ";
       }