Department of Engineering

IDP: Extra Programming

Here are a few warm-up exercises to give you practise on aspects of C++ important to the IDP

Multiple source files and global variables

// Write a function called set_i_to_7 in another file so
// that when the other file and this file are compiled
// together, the resulting program prints "i=7".
// Don't change this file

#include <iostream>
using namespace std;

void set_i_to_7();

int i=0;

int main() {
  set_i_to_7();
  cout << "i=" << i << endl;
}

Bits and bytes

Write a function that given an integer in the range 0 to 255, prints the value in binary. n.b. C++ already has a way to print values in base 16 - e.g.

#include <iostream>
using namespace std;

int main() {
  cout << hex << 90 << endl;
}

Logical and bitwise AND

C++ treats any non-zero value as having the value true when a boolean is expected. Before you run this code, work out what it will print

#include <iostream>
using namespace std;

int main() {
  for (int i=0;i<4;i++)
     for (int j=i;j<4;j++)
        cout << i << " and " << j << " = " << (i and j) << endl <<
        i << " bitand " << j << " = " << (i bitand j) << endl;
}

What happens when you remove the brackets around i and j and i bitand j? Why?

Operators

Work out what's wrong with this program and fix it

#include <iostream>
using namespace std;

int main() {
  int x=1, y=2;
  // Check to see if either x or y is 3
  if (x or y == 3)
    cout << "Either " << x << " is 3, or " << y << " is 3" << endl;

  if (3>4>5)
    cout <<  "3>4>5 is true" << endl;
  else
    cout <<  "3>4>5 is untrue" << endl;
}