Chapter 4 Exercise Set 0: Chapter Review¶
What happens if you call the
countdown
function introduced in the Recursion section with an argument that is a negative number?Draw a stack diagram for
n_lines
, invoked with the parametern
equal to4
.Write a function named
compare
that takes twoint
arguments,a
andb
, and prints out whethera
is greater thanb
,a
is less thanb
, ora
is equal tob
.
Exploring the bitwise operators¶
The following program will help you explore the bitwise operators:
#include <iostream> using namespace std; void print_byte_bits(unsigned char byte) { for (int mask = 128; mask > 0; mask >>= 1) { cout << (mask & byte ? '1' : '0'); if (mask == 16) cout << ' '; } cout << endl; } void show_bitwise_operation(char byte1, char op, char byte2=0) { if (op == '~') { cout << "Showing ~" << int(byte1) << ':' << endl; print_byte_bits(byte1); cout << "---------" << endl; print_byte_bits(~byte1); cout << endl; return; } if (op == 'l' || op == 'r') { cout << "Showing " << int(byte1) << ' '; cout << (op == 'l' ? "<< " : ">> ") << int(byte2) << ':' << endl; print_byte_bits(byte1); cout << "---------" << endl; if (op == 'l') print_byte_bits(byte1 << byte2); else print_byte_bits(byte1 >> byte2); cout << endl; return; } cout << "Showing " << int(byte1) << ' ' << op << ' ' << int(byte2); cout << ':' << endl; print_byte_bits(byte1); print_byte_bits(byte2); cout << "---------" << endl; if (op == '&') print_byte_bits(byte1 & byte2); else if (op == '|') print_byte_bits(byte1 | byte2); else if (op == '^') print_byte_bits(byte1 ^ byte2); else if (op == 'l') print_byte_bits(byte1 << byte2); else if (op == 'r') print_byte_bits(byte1 >> byte2); cout << endl; } int main() { show_bitwise_operation(42, '&', 11); show_bitwise_operation(42, '|', 11); show_bitwise_operation(42, '^', 11); show_bitwise_operation(42, '~'); show_bitwise_operation(42, 'l', 2); show_bitwise_operation(42, 'r', 2); return 0; }
Compile and run this program and study its output.
Notice how the
return
statement is used to end execution of theshow_bitwise_operation
function in two places. Remove the two return statements and use chained conditionals instead, without changing the behavior of the function.Add several additional calls to
show_bitwise_operation
with different operands and operators to explore these operators until you feel you understand what they do.What happens to the least significant (rightmost) bit in a left shift operation? How about the most significant (leftmost) bit in a right shift operation?
Random numbers revisisted¶
Now that you know about the Modulus operator, use it to generate 3 random numbers between 1 and 10. This is a common algorithm, so do a web search for it if you need help figuring it out.