Topic, Task & Test

Fundamentals of Programming using C++


[Top] [Worked Example] [Problems] [Feedback to Author] [TTT Overview]

TTT Problem Set 1

You will recall that, in my opinion, the most important technique for learning to program is actually write programs. Here I present five problems which can be used to provide that practice.

I would encourage you to actually solve each problem before looking at my sample solution and to help you get started I've set out directly below a fully worked example problem including a brief analysis and design phase.

The problems are not difficult and can all be solved using just the tools developed in topics 1 to 11. They require only simple data types (integers, floating point numbers, single characters) and can be solved with combinations of sequential statements, selection structures (if/else) and while loops.

Example Problem (Problem A)

Problem Statement
The average speed for a journey is calculated as the total distance travelled divided by the total time taken. Suppose a journey is taken in a number of steps and each step has its own distance and time.

Write a program which allows a user to enter the distance and time values for any number of steps in a journey. When the user indicates that they have entered all the values the program is to output the overall average speed for the complete journey.

Problem Analysis
An analysis consists of a consideration of:

We take each of these in turn and briefly describe it relative to the given problem.

Input
The solution will need to get a the distances and times from the user, and a value which can be used to terminate input.
Output
The program will have to output a single value which is the average speed for the complete journey
Data
This is the nature of the variables or structures which will be used to store information. We will need variables for input times and distances, for the total distance and time and for the calculated average.
Processes
The main processing control will be a loop which allows the input of a number of distances and times.
Assumptions
We need to make assumptions if any part of the problem is ambiguous. For example, the problem gives no indication of whether the distances and times are integers or can contain fractional parts. Lets assume the latter. The problem does not specify how the user will terminate the input. Let's assume that the input of a negative distance will signal the end of input.
Design
The design of the solution sets out the logical steps which would be followed in a computer program. The result of the design process in an algorithm which could be logically converted into C++ code.

There are a number of formal algorithm description languages like flow charts, pseudocode or NS diagrams which could be used to create a design but I have provided one here using an informal version of pseudocode:

  declare variables
  set the total distance and the total time to zero
  prompt the user for a distance
  input the distance
  while the distance is not negative
    prompt for a time
    input a time
    add the distance to the total distance
    add the time to the total time
    prompt the user for another distance
    input the distance
  endwhile
  if the total distance is not zero
    calculate the average speed (total dist / total time)
    output the average speed
  else
    output a message explaining that the average speed cannot be calculated

Test
We test our design with a desk test. That is, we run the algorithm by hand, using sample inputs and do the calculations manually.

A desk test can be enhanced by the use of a Trace Table which is a technique for recording the values of the variables as the algorithm is tested.

For some sample input, let's assume the user enters the following data:

  distance: 100 km  time: 1.5 hrs
  distance: 50 km   time: 0.8 hrs
  distance: 150 km  time: 2.0 hrs
  distance: -1 km (the sentinel)

With these data, a trace table would look like this:

  VAR           | VALUES
  -------------------------------------
  dist          |   100 50   150  -1
  time          |   1.5 0.8  2.0
  total dist    | 0 100 150  300
  total time    | 0 1.5 2.3  5.3
  average speed |                 56.6
  -------------------------------------
You should dest test the algorithm a number of times including the situation where the user enters a negative value for the distance as the very first input. I leave this as an exercise for you.

When the design phase is over (after adequate testing) you can convert your algorithm into C++ source code, compile it and test it.

Code
For completeness, I present here my solution in C++ to the average speed problem.
// Average speed

#include <iostream.h>

void main( void )
{
  float dist, time;
  float total_dist = 0.0, total_time = 0.0;
  float avg;

  cout << "Enter the first distance (or <0 to end) ";
  cin >> dist;
  while( dist >= 0 )
  {
    cout << "Enter the time taken ";
    cin >> time;
    total_dist += dist;
    total_time += time;
    cout << "Enter the next distance (or <0 to end) ";
    cin >> dist;
  }
  if( total_time != 0 )
  {
    avg = total_dist/ total_time;
    cout << "The overall average is " << avg << endl;
  }
  else
    cout << "Cannot calculate an average speed." << endl;
}


Now try these problems for yourself; before looking at the sample solutions!
[Top] [Worked Example] [Problems] [Feedback to Author] [TTT Overview]

TTT Problems Set 1

Problem B.

In the game of blackjack, players are initially dealt two cards and then extra cards one at a time. Players try to make the total value of their cards as high as possible without exceeding 21. During the dealing, a player says "Hit" to request another card or "Stand" when they require no more cards.

Write a program which acts as the blackjack dealer. The program first outputs two integers representing the two initial cards and then allows the user to enter 'H' for "Hit" or 'S' for "Stand". If the request is "Hit" another integer is output.

The program is to stop when either the user enters 'S' to "Stand" or the total of the output numbers is greater than 21.

All the numbers representing cards are in the range 1..10 inclusive and are generated randomly by the program.

Sample Solution

Problem C

Write a program which classifies users according to their age. The program is to allow entries from any number of users, each one entering their age at the keyboard. Ages less than 18 are classified as "Young", those between 18 and 55 (inclusive) are classified as "Middle" and those above 55 are classified as "Old". When any negative age is entered the program is to output a table showing the three classes and the number of ages in each class, similar to that shown here:
  Class   Tally
  --------------------
  Young    10
  Middle   15
  Old      7
  --------------------
  Total    32

The negative age which is used as a sentinel is not to be included in the calculations.

Sample Solution

Problem D. (similar to NSW HSC paper 1991)

Write a program to process sets of three numbers as follows:

Data is read into the computer in groups of three numbers.

e.g.

27	12	25
13	19	13
15	16	24
21	11	4
..	..	..
0	0	0

For each group of three numbers, the program is to write out the numbers and indicate the smallest number and its position in the group.

The end of the input data is marked by the three numbers 0 0 0, which are detected but not processed further and not printed out.

If more than one number in a group shares the same lowest value, the position of the last occurrence of that value is to be reported.

For the data in the example above, the output should be:

27 12 25
The smallest number was 12 in position 2.
13 19 13
The smallest number was 13 in position 3.

and so on.

Sample Solution

Problem E.

The game of "craps" is essentially a game for one player. In the game, two ordinary six sided dice are thrown and the two numbers showing on their top face are added into a total.

If this total is 7 or 11, the player wins immediately.

If the total is 2 or 3 or 12, the player loses immediately.

If neither of these results occur, then the player notes the result (called their 'point') and then continues to throw the dice until they either win or lose.

A win occurs if the player throws their 'point' again before a 7 is thrown. A lose occurs if a 7 is thown before their 'point' is thrown. Other numbers are ignored.

Write a program to allow a player to play a game of "craps".

Sample Solution


[Top] [Worked Example] [Problems] [Feedback to Author] [TTT Overview]

Feedback

I am interested in hearing your views about the TTT System or any of its content. If you would like to offer any comments or suggestions please email me.
Author:
Errol Chopping echopping@csu.edu.au
Lecturer in Computing
Charles Sturt University - Mitchell
Bathurst NSW 2795
Australia.
Last Update: Apr 4, 1996