Search

6.x — Chapter 6 comprehensive quiz

Words of encouragement

Congratulations on reaching the end of the longest chapter in the tutorials! Unless you have previous programming experience, this chapter was probably the most challenging one so far. If you made it this far, you’re doing great!

The good news is that the next chapter is easy in comparison. And in the chapter beyond that, we reach the heart of the tutorials: Object-oriented programming!

Chapter summary

Arrays allow us to store and access many variables of the same type through a single identifier. Array elements can be accessed using the subscript operator ([]). Be careful not to index an array out of the array’s range. Arrays can be initialized using an initializer list or uniform initialization (in C++11).

Fixed arrays must have a length that is set at compile time. Fixed arrays will usually decay into a pointer when evaluated or passed to a function.

Loops can be used to iterate through an array. Beware of off-by-one errors, so you don’t iterate off the end of your array. For-each loops are useful when the array hasn’t decayed into a pointer.

Arrays can be made multidimensional by using multiple indices.

Arrays can be used to do C-style strings. You should generally avoid these and use std::string instead.

Pointers are variables that store the memory address of (point at) another variable. The address-of operator (&) can be used to get the address of a variable. The dereference operator (*) can be used to get the value that a pointer points at.

A null pointer is a pointer that is not pointing at anything. Pointers can be made null by initializing or assigning the value 0 (or in C++11, nullptr) to them. Avoid the NULL macro. Dereferencing a null pointer can cause bad things to happen. Deleting a null pointer is okay (it doesn’t do anything).

A pointer to an array doesn’t know how large the array they are pointing to is. This means sizeof() and for-each loops won’t work.

The new and delete operators can be used to dynamically allocate memory for a pointer variable or array. Although it’s unlikely to happen, operator new can fail if the operating system runs out of memory, so make sure to check whether new returned a null pointer.

Make sure to use the array delete (delete[]) when deleting an array. Pointers pointing to deallocated memory are called dangling pointers. Dereferencing a dangling pointer can cause bad things to happen.

Failing to delete dynamically allocated memory can result in memory leaks when the last pointer to that memory goes out of scope.

Normal variables are allocated from limited memory called the stack. Dynamically allocated variables are allocated from a general pool of memory called the heap.

A pointer to a const value treats the value it is pointing to as const.

A const pointer is a pointer whose value can not be changed after initialization.

A reference is an alias to another variable. References are declared using an ampersand, but this does not mean address-of in this context. References are implicitly const -- they must be initialized with a value, and a new value can not be assigned to them. References can be used to prevent copies from being made when passing data to or from a function.

The member selection operator (->) can be used to select a member from a pointer to a struct. It combines both a dereference and normal member access (.).

Void pointers are pointers that can point to any type of data. They can not be dereferenced directly. You can use static_cast to convert them back to their original pointer type. It’s up to you to remember what type they originally were.

Pointers to pointers allow us to create a pointer that points to another pointer.

std::array provides all of the functionality of C++ built-in arrays (and more) in a form that won’t decay into a pointer. These should generally be preferred over built-in fixed arrays.

std::vector provides dynamic array functionality that handles its own memory management and remember their size. These should generally be favored over built-in dynamic arrays.

Quiz time

1) Pretend you’re writing a game where the player can hold 3 types of items: health potions, torches, and arrows. Create an enum to identify the different types of items, and a fixed array to store the number of each item the player is carrying (use built-in fixed arrays, not std::array). The player should start with 2 health potions, 5 torches, and 10 arrows. Write a function called countTotalItems() that returns how many items the player has in total. Have your main() function print the output of countTotalItems().

Show Solution

2) Write the following program: Create a struct that holds a student’s first name and grade (on a scale of 0-100). Ask the user how many students they want to enter. Dynamically allocate an array to hold all of the students. Then prompt the user for each name and grade. Once the user has entered all the names and grade pairs, sort the list by grade (highest first). Then print all the names and grades in sorted order.

For the following input:

Joe
82
Terry
73
Ralph
4
Alex
94
Mark
88

The output should look like this:

Alex got a grade of 94
Mark got a grade of 88
Joe got a grade of 82
Terry got a grade of 73
Ralph got a grade of 4

Hint: You can modify the selection sort algorithm from lesson 6.4 -- Sorting an array using selection sort to sort your dynamic array. If you put this inside its own function, the array should be passed by address (as a pointer).

Show Solution

3) Write your own function to swap the value of two integer variables. Write a main() function to test it.

Hint: Use reference parameters

Show Solution

4) Write a function to print a C-style string character by character. Use a pointer to step through each character of the string and print that character. Stop when you hit a null terminator. Write a main function that tests the function with the string literal “Hello, world!”.

Hint: Use the ++ operator to advance the pointer to the next character.

Show Solution

5) What’s wrong with each of these snippets, and how would you fix it?

a)

Show Solution

b)

Show Solution

c)

Show Solution

d)

Show Solution

e)

Show Solution

6) Let’s pretend we’re writing a card game.

6a) A deck of cards has 52 unique cards (13 card ranks of 4 suits). Create enumerations for the card ranks (2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace) and suits (clubs, diamonds, hearts, spades).

Show Solution

6b) Each card will be represented by a struct named Card that contains a rank and a suit. Create the struct.

Show Solution

6c) Create a printCard() function that takes a const Card reference as a parameter and prints the card rank and value as a 2-letter code (e.g. the jack of spades would print as JS).

Show Solution

6d) A deck of cards has 52 cards. Create an array (using std::array) to represent the deck of cards, and initialize it with one of each card.

Hint: Use static_cast if you need to convert an integer into an enumerated type.

Show Solution

6e) Write a function named printDeck() that takes the deck as a const reference parameter and prints the values in the deck. Use a for-each loop.

Show Solution

6f) Write a swapCard function that takes two Cards and swaps their values.

Show Solution

6g) Write a function to shuffle the deck of cards called shuffleDeck(). To do this, use a for loop to step through each element of your array. Pick a random number between 1 and 52, and call swapCard with the current card and the card picked at random. Update your main function to shuffle the deck and print out the shuffled deck.

Hint: Review lesson 5.9 -- Random number generation for help with random numbers.
Hint: Don’t forget to call srand() at the top of your main function.
Hint: If you’re using Visual Studio, don’t forget to call rand() once before using rand.

Show Solution

6h) Write a function named getCardValue() that returns the value of a Card (e.g. a 2 is worth 2, a ten, jack, queen, or king is worth 10. Assume an Ace is worth 11).

Show Solution

7) Alright, challenge time! Let’s write a simplified version of Blackjack. If you’re not already familiar with Blackjack, the Wikipedia article for Blackjack has a summary.

Here are the rules for our version of Blackjack:
* The dealer gets one card to start (in real life, the dealer gets two, but one is face down so it doesn’t matter at this point).
* The player gets two cards to start.
* The player goes first.
* A player can repeatedly “hit” or “stand”.
* If the player “stands”, their turn is over, and their score is calculated based on the cards they have been dealt.
* If the player “hits”, they get another card and the value of that card is added to their total score.
* An ace normally counts as a 1 or an 11 (whichever is better for the total score). For simplicity, we’ll count it as an 11 here.
* If the player goes over a score of 21, they bust and lose immediately.
* The dealer goes after the player.
* The dealer repeatedly draws until they reach a score of 17 or more, at which point they stand.
* If the dealer goes over a score of 21, they bust and the player wins immediately.
* Otherwise, if the player has a higher score than the dealer, the player wins. Otherwise, the player loses (we’ll consider ties as dealer wins for simplicity).

In our simplified version of Blackjack, we’re not going to keep track of which specific cards the player and the dealer have been dealt. We’ll only track the sum of the values of the cards they have been dealt for the player and dealer. This keeps things simpler.

Start with the code you wrote in quiz #6. Create a function named playBlackjack() that returns true if the player wins, and false if they lose. This function should:
* Accept a shuffled deck of cards as a parameter.
* Initialize a pointer to the first Card named cardPtr. This will be used to deal out cards from the deck (see the hint below).
* Create two integers to hold the player’s and dealer’s total score so far.
* Implement Blackjack as defined above.

Hint: The easiest way to deal cards from the deck is to keep a pointer to the next card in the deck that will be dealt out. Whenever we need to deal a card, we get the value of the current card, and then advance the pointer to point at the next card. This can be done in one operation:

This returns the current card’s value (which can then be added to the player or dealer’s total), and advances cardPtr to the next card.

Also write a main() function that plays a single game of Blackjack.

Show Solution

7a) Extra credit: Critical thinking time: Describe how you could modify the above program to handle the case where aces can be equal to 1 or 11.

Hint: It’s important to note that we’re only keeping track of the sum of the cards, not which specific cards the user has.

Show Solution

7b) In actual blackjack, if the player and dealer have the same score (and the player has not gone bust), the result is a tie and neither wins. Describe how you’d modify the above program to account for this.

Show Solution

7.1 -- Function parameters and arguments
Index
6.16 -- An introduction to std::vector

485 comments to 6.x — Chapter 6 comprehensive quiz

  • Paul

    Sorry to ask a basic question, however following issues trying to write my own code I have given up and copying your directly I still can't get 6E to print all the values in the deck could someone please give me some advice

    #include "stdafx.h"
    #include <iostream>
    #include <array>

    enum CardSuit
    {
        SUIT_HEART,
        SUIT_DIAMOND,
        SUIT_SPADE,
        SUIT_CLUB,
        MAX_SUITS,
    };

    enum CardRank
    {
        RANK_2,
        RANK_3,
        RANK_4,
        RANK_5,
        RANK_6,
        RANK_7,
        RANK_8,
        RANK_9,
        RANK_10,
        RANK_JACK,
        RANK_QUEEN,
        RANK_KING,
        RANK_ACE,
        MAX_RANKS,
    };

    struct Card
    {
        CardRank rank;
        CardSuit suit;
    };

    void printCardSuitAndRank(const Card &card)
    {
        switch (card.rank)
        {
        case RANK_2:        std::cout << '2';    break;
        case RANK_3:        std::cout << '3';    break;
        case RANK_4:        std::cout << '4';    break;
        case RANK_5:        std::cout << '5';    break;
        case RANK_6:        std::cout << '6';    break;
        case RANK_7:        std::cout << '7';    break;
        case RANK_8:        std::cout << '8';    break;
        case RANK_9:        std::cout << '9';    break;
        case RANK_10:        std::cout << 'T';    break;
        case RANK_JACK:        std::cout << 'J';    break;
        case RANK_QUEEN:    std::cout << 'Q';    break;
        case RANK_KING:        std::cout << 'K';    break;
        case RANK_ACE:        std::cout << 'A';    break;
        }

        switch (card.suit)
        {
        case SUIT_HEART:    std::cout << 'H';    break;
        case SUIT_DIAMOND:    std::cout << 'D';    break;
        case SUIT_SPADE:    std::cout << 'S';    break;
        case SUIT_CLUB:        std::cout << 'C';    break;
        }
    }

    void printDeck(const std::array<Card, 52> &deck)
    {
        
        for (const auto &card : deck)
        {
            printCardSuitAndRank(card);
            std::cout << ' ';
        }

        std::cout << '\n';
    }

    int main()
    {
        std::array<Card, 52> deck;

        int card = 0;
        for (int suit = 0; suit < MAX_SUITS; ++suit)
        for (int rank = 0; rank < MAX_RANKS; ++rank)
        {
            deck[card].suit = static_cast<CardSuit>(suit);
            deck[card].rank = static_cast<CardRank>(rank);
        }

        printDeck(deck);

        return 0;
    }

  • George

    Totally unrelated, but could anyone share his opinion on "murach's C++ programming" and how good of a book it would be for someone that has read up until here? I'm saying because someone gifted it to me.

  • Gizmo

    I did quiz 1 a little differently than the solution showed. It works, but is this acceptable? (DISCLAIMER: I'm using namespace std because my coworkers use it.)

    Also, are there any suggestions to make it better?

    • Hi Gizmo!

      > is this acceptable?
      Yes

      > I did quiz 1 a little differently
      Arrays aren't usually passed by reference, but you can do so if you like to. You'll learn about easier ways later on.

      > any suggestions
      * Line 18: Looping by value is probably faster than by reference, because you're looping an array of ints, which have a good size for your computer. If you want to loop by reference you should do so by const reference.
      * Line 27: You don't need to specify the array size if you're fully initializing the array.
      * Line 28: Uniform initialization

  • Kio

    Quiz 1. -> solution:

    Quiz 2.

    For Quiz 3.

  • For quiz 3

  • In quiz 2, I cannot use the -> operator. I wonder why?

  • Hi, first of all, thank you very much for these tutorials, I'm really enjoying them!

    Would like to know what you think about my implementation of the control for 1/11 value of a ACE drawn. I thought this can be implemented passing the current value of the hand to

    and then counting an ACE as 1 should the updated value of the hand exceeds 21, and 11 otherwise.

    So, in

    , I update the value of the hand as

    having updated the

    as follows:

  • Sam

    There is an issue with your solution to question 5a. The conditional should be "< 4" instead of "< 5".

    • No. The condition is checked before the loop-body is entered. Using < 4 would cause the loop to never reach the element at index 4.

      • Sam

        Oh sorry, I got confused thinking the array was only 4 elements because only 4 elements were initialised, not realising that the total array length was set to 5. Thanks for correcting me.

  • Reynaldo Concepcion

    Hi! I just finished #7 and I'd like to hear how I can improve it, thanks in advance!

    • Hi Reynaldo!

      * Use enum class
      * Line 42, 43: Avoid global variables
      * Line 47, 168: Use empty curly brackets. @std::string's default constructor is faster.
      * Line 110: You shouldn't print a line break here so the caller can append text on the same line.
      * Initialize your variables with uniform initialization
      * @swapCard can be replaced with @std::swap
      * Prefer constexpr over const
      * Line 133: Comparison of int and @std::size_t
      * @getCardValue: Parameter @card should be const
      * Line 170ff: @std::string::operator==(const char*) is a thing
      * Line 175, 179: Double comparison of @playerChoice to "hit"
      * Line 198: Either I'm missing something, or @isOver is always true when this is reached.
      * Line 200: (a >= b) is already a bool. There's no need for the conditional operator
      * Magic numbers

      • Reynaldo Concepcion

        Okay I appreciate all the suggestions! I'm curious about your comment regarding line 133, is it a suggestion that comparisons should always strictly be the same data type? I can't fully understand the implications of comparing int to std::size_t

        • > is it a suggestion that comparisons should always strictly be the same data type?
          They don't have to be exactly the same type if you know that the comparison is well defined and doesn't behave unexpectedly.
          This isn't the case for comparison of signed/unsigned integers. @std::size_t is an unsigned int.

          You'd think that @s is bigger than @i, because 0 is bigger than -1. But when you compare signed integers to unsigned integers, the integer will be converted to an unsigned integer. This means that actually @i is bigger than @s (Lesson 3.7), so the code prints "i >= s".
          Enable compiler warnings. Read them. If you don't understand what's causing them, google to figure it out or ask here.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]