You are on page 1of 39

CSCI 1120

Introduction to Computing Using C++


Tutorial 3

28th Sep. 2020

1
Outline

• Assignment 2

Introduction to Missionaries and cannibals


Solve the problem step by step
Input & output requirements

• Formatting output

Why do we want to format output?


Format flags
Formatting Floating Points, I/O Manipulators

2
Outline

• Assignment 2

Introduction to Missionaries and cannibals


    Solve the problem step by step
Input & output requirements

• Formatting output

Why do we want to format output?


Format flags
Formatting Floating Points, I/O Manipulators

3
Assignment 2: Missionaries and cannibals
 Introduction
The objective of this assignment is to let you practice the use of variables,
operators, expressions, standard input/output and control flow in C++.

Problem Example <3, 3, 2> ( in classical setting )


• Three missionaries and three cannibals are on one bank of a river.
• One boat that can carry at most two people.
• The missionaries will get eaten if the cannibals ever outnumber the
missionaries on either of the river’s banks
• At least one people is required to drive the boat

Under these constraints, how can the boat be used to safely carry all the
missionaries and cannibals across the river?

4
Assignment 2: Missionaries and cannibals

5
Assignment 2: Missionaries and cannibals

https://www.youtube.com/watch?v=dkJBn0o45vg

6
Assignment 2: Missionaries and cannibals
• The program is played via the console
• instead of a graphical user interface.
• The problem is generalized and ask user to input
• M: the number of missionaries
• C: cannibals
• B: the boat capacity
• The input should be valid
• B must not be < 2
• Unless M > C, for problems with B = 2, M and C must be <= 3
• for problems with B = 3, M and C must be <= 5 or else they have no solution
• Of course, M must always be >= C in a valid problem

7
Assignment 2: Missionaries and cannibals
• Once the valid M, C, B are obtained, the program would
repeatedly prompt the user for 
• how many missionaries to get on the boat.
• how many cannibals to get on the boat.
• It will check whether the input numbers are valid
• The boat available can carry at most B people.
• The cannibals cannot outnumber the missionaries on boat
• The boat cannot cross the river by itself with no people on board
• ……
• and show the current game state.
8
Assignment 2: Missionaries and cannibals

• The aim of the program is not about implementing any solution


search algorithm to solve the puzzle (which is beyond our scope) but
simply supporting the user to play the game.

• (Optional:) In case you are looking for some algorithms to solve M&C
puzzles, you may look at this reference. 
https://flipkarma.com/media_dir/main_documents/Misionaries_And_
Cannibals_Report.pdf
 
  
9
Assignment 2: Missionaries and cannibals
• Assume that all people are on the left bank initially.
• The current game state can be represented by ⟨m, c, b⟩
• m denotes the counts of missionaries on the left bank
• c denotes the counts of cannibals on the left bank
• b equals 1 or 0 represents whether the boat is on the left or on the right bank

• ⟨3, 3, 1⟩: the initial state vector when the game starts.
• ⟨0, 0, 0⟩: means that all the people and the boat are not on the left
bank. They have all crossed the river!

10
Assignment 2: Missionaries and cannibals

<3, 3, 1>
<2, 2, 0>
<3, 2, 1>
<3, 0, 0>
<3, 1, 1>
state <1, 1, 0>
transition <2, 2, 1>
<0, 2, 0>
<0, 3, 1>
<0, 1, 0>
<0, 2, 1>
<0, 0, 0>
11
Assignment 2: Missionaries and cannibals

You win the game upon reaching the state ⟨0, 0, 0⟩ whereas you lose the game
whenever the missionaries on either bank are outnumbered by the cannibals there,
i.e. m < c and M - m < C - c. 

12
Assignment 2: Missionaries and cannibals
 Program Specification
• The program should obtain three numbers as
user input which control the number of
missionaries (M), the number of cannibals (C)
and the boat capacity (B) at the beginning. These
numbers have to be validated against the criteria
stated on p.1 to ensure that the game will have a
solution before the game gets started. Also, M
and C must be >= 1 to be meaningful.

• There are many combinations of possible inputs.


Please remember there is a sample program
executable posted on Blackboard.
13
Assignment 2: Missionaries and cannibals
 Program Specification
• Then it starts a loop to prompt the user to enter
two numbers, namely mb and cb, which represent
the number of missionaries and cannibals to get
on the boat. (The sum of mb and cb is bounded by
B and is at least 1 (for rowing the boat)). Also, mb
must be >= cb for missionaries aboard not to be
eaten. Of course, mb and cb cannot exceed the
number of available missionaries and cannibals
on the bank concerned. Your program must check
against these to assure a valid boat trip.  

• There are many combinations of possible inputs.


Please remember there is a sample program
executable posted on Blackboard.
14
Assignment 2: Missionaries and cannibals
 Program Specification
• Upon receiving a valid pair of mb and cb, the
program computes the current game state ⟨m,
c, b⟩ and prints the number of missionaries and
cannibals on both banks and the boat position
to the console in a specific format (see the
Sample Runs section).
• It will repeat prompting the user for new boat
trip inputs and game state handling until the
state becomes ⟨0, 0, 0⟩ or the game losing
condition stated above is met, i.e. some
missionaries get eaten! A game winning or
losing message should be printed accordingly. 

• There are many combinations of possible inputs.


Please remember there is a sample program
executable posted on Blackboard. 15
Assignment 2: Missionaries and cannibals
 Output Formatting Requirements
• To display the game statistics neatly, the state,
missionary and cannibal counts on either bank
are all right-aligned, each in a fixed width that is
set in the following manner. Suppose that M has
x digits, and C has y digits.

• The field widths for the number of missionaries


and cannibals on both banks will be set to x and
y respectively. The field width for the state
counter will be set to be maximum(x, y) + 1.
Padding is added to the left of those values with
# digits < the field width.

• Also, there is a single space after the word


“State” and every comma.
16
Assignment 2: Missionaries and cannibals
 Assumptions and Hints

• You can assume the user inputs are always non-negative integers bounded
by 1000. There is no need to validate the inputs against values that go
beyond this assumption, e.g. "abc", "@#&", 99.9, -1, 1001, 9,999,999, etc.

• To achieve the right-alignment stated above, you can make use of a


standard library’s function std::setw(…). To use it, you have to add
#include <iomanip> at your program’s beginning.

17
Assignment 2: Missionaries and cannibals
 Assumptions and Hints
• Suppose the field width for the state counter is set to 2. In case the player
keeps playing the game for so many rounds such that the state counter
exceeds 2 digits, the output of the rest is simply shifted to the right
accordingly. See the example below: 

•  To know the number of digits of a number, you may use any working
method except for third party API, e.g. counting with a loop, or converting
into a string and get the string’s length.
18
Assignment 2: Missionaries and cannibals
 Sample Runs
In the following sample runs, the
blue text is user input and the
other text is the program
printout. You can try the
provided sample program for
other input.
Your program output should be
exactly the same as the sample
program (same text, symbols,
letter case, spacings, etc.).
Note that there is a space after
the ‘:’ in the program printout.

19
Assignment 2: Missionaries and cannibals
 Sample Runs
In the following sample runs, the blue text is user input and the other text is the program printout. You can try the
provided sample program for other input. Your program output should be exactly the same as the sample program
(same text, symbols, letter case, spacings, etc.). Note that there is a space after the ‘:’ in the program printout.

20
Assignment 2: Missionaries and cannibals
 Sample Runs
• There are many combinations of possible inputs.
Please check your program correctness against the
results produced by our sample program executable
posted on Blackboard.

21
Assignment 2: Missionaries and cannibals
 Submission and Marking
• Your program source file name should be rowboat.cpp. Submit the file in Blackboard
(https://blackboard.cuhk.edu.hk/). 

• Insert your name, student ID, and e-mail as comments at the beginning of your source file.

• You can submit your assignment multiple times. Only the latest submission counts.

• Your program should be free of compilation errors and warnings. Your program should
include suitable comments as documentation.

• Do NOT plagiarize. Sending your work to others is subject to the same penalty for copying
work.

22
Outline

• Assignment 2

Introduction to Missionaries and cannibals


    Solve the problem step by step
Input & output requirements

• Formatting output

Why do we want to format output?


Format flags
Formatting Floating Points, I/O Manipulators

23
Why do we want to format output?

• Output

• Do we really care about the 40-th digit of pi?


No! – so why not make the output cleaner, for example,
output just two decimal place only? (3.14)

24
Format flags

• Flags are like switches (which can be turned on/off).

• Based on the values of the formatting flags, an output


stream object decides how to output a value.

25
1 int number = 1023; 1023
2 3ff
3 cout.setf( ios::dec ); 3FF
4 cout << number << endl; 1777
5 cout.unsetf( ios::dec ); 1
6 true
7 cout.setf( ios::hex );
8 cout << number << endl;
9
10 cout.setf( ios::uppercase );
11 cout << number << endl;
12 cout.unsetf( ios::hex );
13
14 cout.setf( ios::oct );
15 cout << number << endl;
cout.unsetf( ios::oct );
16
17
cout << true << endl;
18
cout.setf( ios::boolalpha );
19
cout << true << endl;
20
Using format flags to format integers 26
Format flags
• boolalpha -- Boolean values can be input/output using the
words "true" and "false".

• dec / oct / hex– Numeric values are displayed in decimal / octal /


hexadecimal.

• fixed – Display floating point values using normal notation (as


opposed to scientific).

• scientific – Display floating point values using scientific


notation

• internal – Numeric value is padded to fill a field, spaces are


inserted between the sign and base character.

• left / right – Output is left/right justified


27
• showbase – Display the base of all numeric values

• showpoint – Display a decimal and extra zeros, even when not


needed

• showpos – Display a leading plus sign before positive numeric


values

• skipws – Discard whitespace characters (spaces, tabs, newlines)


when reading from a stream

• unitbuf – Flush the buffer after each insertion

• uppercase – Display the "e" of scientific notation and the "x" of


hexidecimal notation as capital letters
28
Formatting Floating Points
• fixed or scientific
• showpoint flag has no effect (always assume showpoint is
on)

• Default (When both fixed and scientific flags are off)


• If showpoint is off, won't print unnecessary trailing zeros
after decimal places.
• Automatically switch between fixed and scientific
notation depends on the magnitude of the value.

29
1 double num = 1.234; 100.000
2 // Default precision is 6 1.234000e+00
3 cout.setf( ios::showpoint ); 1.234000
4 cout << 100.0 << endl; 1.234000000000
5 1.234
6 cout.setf( ios::scientific ); 100
7 cout << num << endl; 1e+14
8 cout.unsetf( ios::scientific );
9
10 cout.setf( ios::fixed );
11 cout << num << endl;
12 cout.precision(12); // Set precision to 12
13 cout << num << endl;
14 cout.unsetf( ios::fixed );
15
16 // Use the "default" format for floating point numbers
17 cout.unsetf( ios::showpoint );
18 cout << num << endl;
19 cout << 100.0 << endl;
20 cout << 100000000000000.0 << endl;
Example: Using format flags to format floating point numbers 30
1 123
2 int main() { 1.00000
3 123.000
4 cout << 123.0 << endl;
5 cout.setf(ios::showpoint);
6 cout << 1.0 << endl;
7 cout << 123.0 << endl;
8
9 return 0;
10 }
11
12
13
14

Flag states are carried along with the stream object.

It is important to make sure the flag states remain unchanged


after local use of the stream object. 31
I/O Manipulators

• We can also use manipulators to manipulate flags indirectly

• For example, to set the "dec" flag, we can write


cout << dec;

• Some of the manipulators are defined in <iostream> and some are


defined in <iomanip>

32
1 int number = 0x03ff; 1023
2 3ff
3 cout << dec << number << endl; 3FF
4 cout << hex << number << endl; 1777
5 cout << uppercase << number << endl; 1
6 cout << oct << number << endl; true
7
8 cout << noboolalpha << true << endl;
9 cout << boolalpha << true << endl;
10 cout << endl;
11

Example: Using manipulators to format integers

33
1 double num = 1.234;
2
3 cout << showpoint << 100.0 << endl;
4 cout << scientific << num << endl;
5 cout << fixed << num << endl;
6
7 cout << setprecision(12) << num << endl;
8
9 // Reset to the "default" floating point format
10 cout.unsetf( ios::scientific | ios::fixed );
11 100.000
12 cout << noshowpoint << num << endl; 1.234000e+00
13 cout << 100.0 << endl; 1.234000
14 1.234000000000
15 1.234
16 100

• Example: Using manipulators to format


floating point numbers
34
1 cout << "----------==========" << endl;
2
3 // Left justified the value in the reserved space
4 cout << left;
5 cout << setw(10) << 123 << setw(10) << "ABC" << endl;
6
7 // Right justified the value in the reserved space
8 cout << right;
9 cout << setw(10) << 123 << setw(10) << "ABC" << endl;
10
11
12 ----------==========
123 ABC
123 ABC

• setw(field_width) only applies to the next value inserted to the stream.


• Without setw(field_width) or when field_width is too small, left/right
justification has no effect.
35
Manipulators defined in <iostream>
Manipulator Description Input Output
boolalpha Turns on the boolalpha flag X X
dec Turns on the dec flag X X
endl Output a newline character, flush the stream X
ends Output a null character X
fixed Turns on the fixed flag X
flush Flushes the stream X
hex Turns on the hex flag X X
internal Turns on the internal flag X
left Turns on the left flag X
noboolalpha Turns off the boolalpha flag X X
noshowbase Turns off the showbase flag X
noshowpoint Turns off the showpoint flag X
noshowpos Turns off the showpos flag X

36
noskipws Turns off the skipws flag X
nounitbuf Turns off the unitbuf flag X
nouppercase Turns off the uppercase flag X
oct Turns on the oct flag X X
right Turns on the right flag X
scientific Turns on the scientific flag X
showbase Turns on the showbase flag X
showpoint Turns on the showpoint flag X
showpos Turns on the showpos flag X
skipws Turns on the skipws flag X
unitbuf Turns on the unitbuf flag X
uppercase Turns on the uppercase flag X
ws Skip any leading whitespace X

37
Manipulators defined in <iomanip>
Manipulator Description Input Output
resetiosflags( long f ) Turn off the flags specified by f X X
setbase( int base ) Sets the number base to base X
setfill( char ch ) Sets the fill character to ch X
setiosflags( long f ) Turn on the flags specified by f X X
Sets the number of digits of
setprecision( int p ) X
precision
setw( int w ) Sets the field width to w X

38
Thanks

Q&A

39

You might also like