A short introduction to computer programming, using C++

Roger Mitton, Birkbeck, University of London

Answers to exercises

1A

(a) cout << endl;

(b) cout << "Hickory" << endl << "Dickory" << endl << "Dock" << endl;

(c)	#include <iostream>
	using namespace std;
	int main()
	{   cout << "Please key in two numbers separated by a space: ";
	    int x, y;
	    cin >> x >> y;
	    cout << y << " " << x << endl;
	}

1B

#include <iostream>
using namespace std;
int main()
{   int x, y;
    cout << "Please key in a number: ";
    cin >> x;
    cout << "And now key in another: ";
    cin >> y;
    cout << "The sum is " << x + y << endl;
    or you could have
    int sum = x + y;
    cout << "The sum is " << sum << endl;
}

2A

5
7
12
10
2
Arithmetic Exception      (attempt to divide by zero)

2B

BBCOK
C++No. Can't have "+" in an identifier.
y2kOK
Y2KOK, and different from y2k.
oldOK
newNo. new is a keyword.
3GLNo. Can't begin with a digit.
a.outNo. Can't have a "." in an identifier.
removeOK, though delete is a keyword.
first-choiceNo. Can't have a "-".
2nd_choiceNo. Can't begin with a digit.
third_choiceOK
constantOK. const is a keyword, but constant is OK.
UNIONOK, though union (lower-case) is a keyword.

2C

real art
7

2D

falseNumerals come before letters
trueUpper-case come before lower-case
falseUpper-case 'B' before lower-case 'b'
trueASCII table puts '$' before '&'
falseSpace comes before apostrophe

2E

#include <iostream>
using namespace std;
int main()
{   int husband, wife;
    cout << "Please key in the husband's salary: ";
    cin >> husband;
    cout << "And now key in the wife's: ";
    cin >> wife;
    if (husband + wife > 40000)
         cout << "You are due for the higher rate." << endl;
    else cout << "You are not due for the higher rate." << endl;
}

2F

if (exammark >= 40)
{    cout << "A satisfactory result" << endl;
     cout << "You may proceed with your project." << endl;
}
else
{    cout << "I'm afraid you have failed." << endl;
     cout << "You may re-enter next year." << endl;
}

2G

#include <iostream>
using namespace std;
int main()
{   cout << "Please key in two numbers separated by a space: ";
    int x, y;
    cin >> x >> y;
    if (y == 0)
         cout << "Cannot divide by zero." << endl;
    else if (x % y == 0)
             cout << "Yes" << endl;
         else cout << "No" << endl;
}

2H

#include <iostream>
using namespace std;
int main()
{   cout << "Please key in an integer representing a 24-hour time," << endl;
    cout << "eg 1415 represents 2.15 pm.  Midnight is zero: ";
    int time;
    cin >> time;
    if (time < 0)
         cout << "Cannot be negative" << endl;
    else if (time >= 2400)
         cout << "Cannot be >= 2400" << endl;
    else
    {    int hours = time / 100, mins = time % 100;
         if (mins >= 60)
             cout << "Cannot have minutes >= 60." << endl;
         else if (hours >= 21)
             cout << "Working late?" << endl;
         else if (hours >= 17)
             cout << "Good evening" << endl;
         else if (hours >= 12)
             cout << "Good afternoon" << endl;
         else if (hours >= 8)
             cout << "Good morning" << endl;
         else if (hours >= 5)
             cout << "Up early?" << endl;
         else cout << "Get a life." << endl;
    }
}

3A

#include <iostream>
using namespace std;
int main()                             or
{   int n = 1;                         int n = 0;
    while (n <= 10)                    while (n < 10)
    {    cout << n * n << endl;        {    n = n + 1;
         n = n + 1;                         cout << n * n << endl;
    }                                  }
}

3B

(x == 5 and y == 10)false
(x < 0 or y > 15)true
(y % x == 0 and s.length() == 8)true
(s.substr(1,3) == "Bir" or x / y > 0)false (s.substr(1,3) is "irk", and x / y gives integer division)

3C

#include <iostream>
using namespace std;
int main()
{    bool finished = false;
     int count = 0;
     while (not finished)
     {    int num;
          cin >> num;
          if (cin.fail())
               finished = true;
          else
               count = count + 1;
     }
     cout << "Number of numbers was " << count << endl;
}

X1

The program takes a series of integers as its input and outputs the largest of them. If you can't see how it does it, trace through it with various possible inputs, such as 1 2 3 4, 4 3 2 1, 1 4 2 3.

X2

It will not work if all the integers are negative. It will say, incorrectly, that the largest was zero. It will also output zero if there is no input at all. The following program will work correctly in both these cases:
#include <iostream>
using namespace std;
int main()
{    bool empty = false, finished = false;
     int max, num;
     cin >> num;
     if (cin.fail())
           empty = true;
     else  max = num;
     while (not empty and not finished)
     {    cin >> num;
          if (cin.fail())
               finished = true;
          else
               if (num > max)
                     max = num;
     }
     if (empty)
           cout << "No input" << endl;
     else if (not cin.eof())
           cout << "Invalid input" << endl;
     else  cout << "Largest was " << max << endl;
}

X3

#include <iostream>
using namespace std;
int main()
{    bool finished = false;
     int count = 0;
     while (not finished)
     {    int num;
          cin >> num;
          if (cin.fail())
               finished = true;
          else if (num == 100)
               count = count + 1;
     }
     cout << "Number of times 100 occurred was " << count << endl;
}

X4

#include <iostream>
#include <string>
using namespace std;
int main()
{    bool finished = false;
     string s, longest;
     int maxlen = 0;
     while (not finished)
     {    getline(cin,s);
          if (cin.fail())
               finished = true;
          else if (s.length() > maxlen)
               {     maxlen = s.length();
                     longest = s;
               }
     }
     cout << longest << endl;
}

X5

#include <iostream>
#include <string>
using namespace std;
int main()
{    bool finished = false;
     int curr, prev;
     cin >> prev;
     while (not finished)
     {    cin  >> curr;
          if (cin.fail())
               finished = true;
          else
          {     if (curr == prev)
                      cout << "Same" << endl;
                else if (curr > prev)
                      cout << "Up" << endl;
                else  cout << "Down" << endl;
                prev = curr;
          }
     }
}

4A


int triplus(int x)
{	return x * 3 + 1;	// precedence of operators ensures (x * 3) + 1, which is what we want
}

4B


string lastpart(string s, int n)
{	if (n > s.length())
		return s;
	else	return s.substr(s.length() - n);
}

4C


void display(int x, int y)
{	int small = x, large = y;
	if (x > y)
	{	large = x;
		small = y;
	}
	cout << "The sum is " << large + small << endl;
	cout << "The difference is " << large - small << endl;
	cout << "The product is " << large * small << endl;
	if (small == 0)
		cout << "Cannot divide by zero" << endl;
	else	cout << "The quotient is " << large / small <<  " with remainder " << large % small << endl;
}

4D


string middle(string s)
{	string empty_string;   // initialised by default to empty string
	if (s.length() < 3)
		return empty_string;   // or just return ""; (with no space between the quote marks)
	else return s.substr(1, s.length() - 2);
}

4E


void stretch(string s)
{	if (s.length() == 0)
		return;
	cout << s.substr(0,1);
	int	n = 1;
	while(n < s.length())
	{	cout << " " << s.substr(n,1);
		n = n + 1;
	}
	cout << endl;
}

4F


#include <iostream>
#include <string>
using namespace std;

string firstpart(string s, int n)
{	return s.substr(0, n);
}

int main()
{	string sg;
	cout << "Please key in a string: ";
	cin >> sg;
	int	n = 1;
	while(n <= sg.length())
	{	cout  << firstpart(sg, n) << endl;
		n = n + 1;
	}
}