# Examples

## Hello world

Here we have the program that, traditionally, is the first thing you read in any new programming language: a program to print “Hello, world!” to the console.

#include <iostream>
using namespace std;

int main() {
cout << "Hello, world!" << endl;
return 0;
}


## Mid-term test questions

Here are some sample questions from previous mid-term tests. They may not all map to what we’ve learned so far in this course (we had covered things in a slightly different order), but I hope they’ll be helpful to you.

### Types

What type(s) of variable should be used to represent each of the following values?

• the number of students enrolled in a course
• the name of a student enrolled in a course
• the length of time that a robot needs to drive 10 cm
• the current date

### Mystery functions

/**
* @param x  any finite real value
* @returns  the square root of x
*/
double sqrt(double x);

double baz(double x, double y)
{
return sqrt(x * x + y * y);
}


What is the value of baz(hi,ho) if hi=3.0 and ho=4.0? Describe what the function baz does, i.e., what would be a good name for baz?

int main()
{
int x = 42;
int y = 42 % 12;
int z = 15 / y;
x = x % z;

cout
<< "x: " << x << endl
<< "y: " << y << endl
<< "z: " << z << endl
;

return 0;
}


What does this program output to the console? (note: this question required the use of the modulus (%) operator, which we haven’t covered yet, but which calculates the remainder of dividing the left by the right)

### Errors

The following function is intended to calculate the time that an aircraft needs to fly in order to reach its destination. However, this function contains several errors. Identify at least four errors in the function. For each error, specify whether it is a syntax error or a logical error.

/**
* Calculates the time required to fly to a destination, based on
*
* @param   distance       how far we need to travel [nm, i.e., nautical miles]
* @param   speed          how fast we are flying [knots, i.e., nm/h]
* @param   headwinds      how fast the wind is flying in our face [knots]
*
* @return  the time required to reach the destination [h]
*/
int flightTime(int distance, int speed, headwinds)
{
int relativeSpeed = speed - headwinds
distance = 300;
int time = distance / speed;

return time;
}


### Software design

#### Student number

A student number at Memorial is a nine-digit number composed from two numbers: the year a student enrolled and a serial number that is unique in that year. Write the contract for a function that calculates a student number for a student, given the year they enrolled and the unique serial number. Do not write more than the contract for the function: any implementation code will not be graded.

#### Square root

Write the contract for a function that calculates the square root of a real number (i.e., a floating-point number). Recall that the contract of a function includes both a descriptive comment and a function prototype.

Do not write more than the contract for the function: any implementation code will not be graded.

### Software implementation

#### LC circuits

When designing resonant LC (inductive-capacitive) circuits, the resonant frequency $\omega_0$ is given by:

$$\omega_0 = \frac{1}{\sqrt{L C}},$$

where $L$ is a value of inductance and $C$ is a value of capacitance. Assuming that the desired resonant frequency and capacitance are known, we can solve for inductance as follows:

$$L = \frac{1}{\omega_0^2 \cdot C}.$$

Using this equation, and given values double frequency and double capacitance, write a C++ expression for the inductance required in the circuit.

#### Ideal gas pressure

In thermodynamics, the ideal gas law states:

$$PV = nRT$$

where $P$ stands for pressure, $V$ stands for volume, $n$ stands for amount (in mols), $R$ is the ideal gas constant $8.31446~\textrm{L} \cdot \textrm{kPa} \cdot \textrm{K}^{−1} \cdot \textrm{mol}^{−1}$ and $T$ is temperature (in degrees Kelvin).

Define a C++ function to calculate the \textbf{pressure} of an ideal gas given its volume, amount and temperature.

#### Critical buckling stress

In structural engineering, the Critical Buckling Stress for a column can be determined using the following equation in the Load and Resistance Factor Design method:

$$F_{cr} = \begin{cases} (0.658) ^ {\lambda_c^2} F_y & \lambda_c \leq 1.5 \\\ \frac{0.877}{\lambda_c^2} F_y & \lambda_c > 1.5 \end{cases}$$

in which $\lambda_c$ is the *slenderness ratio}, a measure of how slender the column is, and $F_y$ is the *yield force} at which the column’s material will fail. Define a C++ function to calculate the critical buckling stress of a column.

#### Rudder control

Consider a ship that is steered in a particular direction but has wind, current and other forces pushing it off course. It is possible to automatically steer the ship with software, compensating for the effects of wind, etc., using control theory ( this is, in fact, one of the earliest motivations for the formal study of PID controllers in control theory). Assume that you are contributing to the design of such a control system.

Note: you do not need to implement anything in this question.

##### Part A (8 marks)

Write contracts (comment and prototype) for functions that your code could use to:

• query the ship’s current heading and
• change the rudder’s angular speed.
##### Part B (12 marks)

One type of control system that can be used for such an application is the proportional-integral-derivative (PID) controller. It works by repeatedly measuring a value (in this case, the ship’s heading), calculating error (the difference between the actual and desired headings) and then minimizing that error:

1. as measured as this moment (using a proportional term),
2. as accummulated over time (using an integral term) and
3. as predicted in the future given the current change in value (using a derivative term).

If $e(t)$ is the error at a given time and $K_p$, $K_i$ and $K_d$ are constants that give different “weights” to the three terms described above, we can choose a rudder angular speed $u(t)$ using the following equation:

$$u(t) = K_p e(t) + K_i \int_{\tau=0}^t e(\tau) d\tau + K_d \frac{d e(t)}{d t}$$

When implemented in software, a PID controller’s integration is replaced by summation ($\sum$) and differentiation is replaced by the difference with the previous error value. Describe the algorithm for such a software PID controller, assuming that $K_p$, $K_i$ and $K_d$ have already been determined for you. You may also assume that the functions that you described in the previous part are available for your use.

## Loops

### Printing numbers:

void printNumbersUpTo(int n)
{
int i = 0;

while (i <= n)
{
cout << i << endl;
i = i + 1;
}
}


### Factorial:

double factorial(int number)
{
double factorial = 1.0;

while (number > 0)
{
factorial = factorial * number;
number = number - 1;
}

return factorial;
}


## Further functions

### Pass-by-reference

/**
* Measure various properties of the current weather.
*
* @param[out]     temperature reading [degrees C]
*/
void weather(double& temperature, double& humidity);


### Functional decomposition

/**
* Calculates the volume of a washer-shaped object.
*
* @param     r1     radius of the washer
* @param     r2     radius of the washer's hole [same linear unit as r1]
*
* @pre r2 > 0, r2 < r1
*
* @returns   total volume [same linear unit cubed]
*/
double washerVolume(double r1, double r2, double depth);

/**
* Calculates the area of a circle.
*
*
* @returns the area of the circle [units of radius squared]
*/


## Arrays

### Array summation

double sum(double values[], int length)
{
double sum = 0;
int i = 0;

while (i < length)
{
sum += values[i];
}

return sum;
}


### Array printing

void printArray(double values[], int length)
{
cout << "values: " << values << endl;

int i = 0;
while (i < length)
{
cout << "element " << i << " is: " << values[i] << endl;
i++;
}
}


### Averaging

double average(double values[], int length)
{
if (length == 0)
{
return 0;
}

double sum = 0;

// The version with a for loop:
for (int i = 0; i < length; i++)
{
sum += values[i];
}

// The version with a while loop:
/*
int i = 0;
while (i < length)
{
sum += values[i];
i++;
}
*/

return sum / length;
}


### Standard deviation

Note: this version assumes (i.e., it should have a precondition) that the array is not empty.

double stddev(double values[], int length)
{
double avg = average(values, length);
double sum = 0;

for (int i = 0; i < length; i++)
{
sum += pow(values[i] - avg, 2);
}

return sqrt(sum / length);
}