9.x — Chapter 9 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.

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. Range-based for-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_view and 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 indirection 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 nullptr (before in C++11, 0) to them. Avoid the NULL macro. Indirection through 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 it is pointing to is. This means sizeof() and range-based for-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. If you’re writing software for a memory-limited system, make sure to check if new was successful.

Make sure to use the array delete (delete[]) when deleting an array. Pointers pointing to deallocated memory are called dangling pointers. Using the wrong delete, or indirection through a dangling pointer causes undefined behavior.

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 an indirection and normal member access (.).

Void pointers are pointers that can point to any type of data. Indirection through them is not possible 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, handles its own memory management and remembers its size. These should generally be favored over built-in dynamic arrays.

Thanks to iterators, we don’t have to know how a container is implemented to loop through its elements.

The algorithms library helps us to save a lot of time by providing many off-the-shelf functions. In combination with iterators (and later lambdas), the algorithms library is an important part of C++.

Quiz time

To make the quizzes a little easier, we have to introduce a couple of new algorithms.

std::reduce applies a function, by default the + operator, to all elements in a list, resulting in a single value. When we use the + operator, the result is the sum of all elements in the list. Note that there’s also std::accumulate. std::accumulate cannot be parallelized, because it applies the function left-to-right. std::reduce segments the list, which means that the function is applied in an unknown order, allowing the operation to be parallelized. If we want to sum up a list, we don’t care about the order and we use std::reduce.

Author's note

std::reduce is currently not fully implemented in all major standard libraries. If it doesn’t work for you, fall back to std::accumulate.

std::shuffle takes a list and randomly re-orders its elements.

Possible output

2 1 4 3

Question #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 an std::array to store the number of each item the player is carrying (The enumerators are used as indexes of the 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() as well as the number of torches.

Show Solution

Question #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. Create a std::vector 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:


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

You can assume that names don’t contain spaces and that that input extraction doesn’t fail.

Show Solution

Question #3

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

Show Hint

Show Solution

Question #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 the null terminator. Write a main function that tests the function with the string literal “Hello, world!”.

Show Hint

Show Solution

Question #5

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


Show Solution


Show Solution


Show Solution


Show Solution


Show Solution

Question #6

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

a) 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). Those enumerators will not be used to index arrays.

Show Solution

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

Show Solution

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

Show Hint

Show Solution

d) 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. Do this in a function named createDeck and call createDeck from main. createDeck should return the deck to main.

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

Show Solution

e) Write a function named printDeck() that takes the deck as a const reference parameter and prints the cards in the deck. Use a range-based for-loop. When you can printDeck with the deck you generated in the previous task, the output should be

2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC AC 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD AD 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH AH 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS AS

If you used different characters, that’s fine too.

Show Solution

f) Write a function named shuffleDeck to shuffle the deck of cards using std::shuffle. Update your main function to shuffle the deck and print out the shuffled deck.

Reminder: Only seed your random number generator once.

Show Solution

g) 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

Question #7

a) 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(). This function should:

  • Accept a shuffled deck of cards as a parameter.
  • Implement Blackjack as defined above.
  • Returns true if the player won, and false if they lost.

Also write a main() function to play a single game of Blackjack.

Show Solution

Once you’ve solved the quiz, have a look at some of the most common mistakes:

Show Hint

b) 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.

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

c) 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

10.1 -- Function parameters and arguments
9.25 -- Introduction to standard library algorithms

1,116 comments to 9.x — Chapter 9 comprehensive quiz

  • Robby Sodhi

    gives me: "Binary: '=' no operator found which takes left hand operator of type _Ty (or there is no acceptable conversion)"

    if you need any more of my code let me know but I am pretty sure the error is on the std::shuffle() line

  • itsmedio

    Here's my solution to 6d using only one for loop and less variables. Took me a bit because I'm still not super familiar with when to use refs or not. If there's a general rule for this I would love to know.

    • nascardriver

      If you create a new variable, eg. in a loop or as a parameter, you have to choose between creating a copy and creating a reference.

      If you want to modify the original variable, you have to use a non-`const` reference. Without the reference, you'd only modify the copy.

      If you don't want to modify the variable:
      If the type is fundamental (`int`, `float`, etc. the types without a `std::` prefix and no includes), or is fast to copy by design (eg. `std::string_view`), use a copy.
      Otherwise (For user-defined types (That includes types defined in the `std` namespaces)), use a `const` reference.

  • kio

    Mine answer for Q6

    Compiler settings are not set properly.
    You last function for the retrievel of the value is brilliant. I was thinking about implementing the same, but was confused with the values of the JACK, QUEEN, KING AND ACE to be, 12,13,14 and 11 respectively.

  • kio

    Hi Alex, the values for the enums for Q6:a, should be lowercase, based on the chapter8:2
    "Enumerators must be given names, and typically use the same name style as constant variables. Sometimes enumerators are named in ALL_CAPS, but doing so is discouraged, because it risks collisions with preprocessor macro names."

    Thanks :)

  • rs1234

    what should i do if i cant do most of these quizes? continue or just start over the whole chapter?

    • nascardriver

      If you can't do these quizzes you probably won't be able to do the next ones. If you read the solution and think "Now I understand", try again tomorrow with a slightly different quiz if you can think one up, otherwise just try this one again.

  • im still new in c++
    but in Q6
    u using std::array as type how is that?i dont  understand ,we never use array(std::array )as a type before ,and now we do ,i hope u explain to me
    [/code]#include <array>

    // We'll need these many more times, create an aliases.
    using deck_type = std::array<card, 52="">;
    using index_type = deck_type::size_type;

    deck_type createDeck()//Here
      deck_type deck{};

      // We could initialize each card individually, but that would be a pain.  Let's use a loop.

      index_type card{ 0 };

      auto suits{ static_cast<int>(CardSuit::MAX_SUITS) };
      auto ranks{ static_cast<int>(CardRank::MAX_RANKS) };

      for (int suit{ 0 }; suit < suits; ++suit)
        for (int rank{ 0 }; rank < ranks; ++rank)
          deck[card].suit = static_cast<cardsuit>(suit);
          deck[card].rank = static_cast<cardrank>(rank);

      return deck;

    int main()
      auto deck{ createDeck() };

      return 0;

  • Unthing

    in Question #6
    im still new of c++
    i dont  understand how u use std::array as tyep
    std::arry is array
    we never did use it before in all this website

  • DaveGuy

    On question 2, my solution runs like this
    #include <iostream>
    #include <string>
    #include <algorithm>

    struct Students
        std::string firstName{};
        int examGrade{};

    Students studentAdd()
        Students student{};
        std::cout << "Enter first name: ";
        std::cin >> student.firstName;
        std::cout << "Enter the student's test score: ";
        std::cin >> student.examGrade;

        return student;

    bool comparison(const Students& stud1, const Students& stud2)
        return (stud1.examGrade > stud2.examGrade);

    int main()
        std::cout << "How many students are in your class? ";
        int numStuds{};
        std::cin >> numStuds;

        std::vector <Students> myClass(numStuds);

        for (int num{ 0 }; num < numStuds; ++num)
   = studentAdd();

        std::cout << std::endl;    

        std::sort(myClass.begin(), myClass.end(), comparison);

        for (Students student: myClass)
            std::cout << student.firstName << " got a grade of " << student.examGrade << '\n';
        std::cout << std::endl;
        return 0;

    I realize that there are multiple solutions to most problems, but this seems simpler and does not require me to use the "using ..." statement, which I have not mastered. Perhaps you might help me understand why the use of that "using ..." is more efficient. Thanks, Dave

    • nascardriver

      If you compiler is configured properly, your code should cause a warning similar to

      To fix this, you need to cast `numStuds` (Avoid abbreviations, name variable descriptively) to `std::vector<Students>>::size_t`. The avoid the repetition of `std::vector<Students>`, we're using a type alias.

  • abcdaf

    Hi, it seems like there are no errors in my code at all but when i try to build it, it fails and it also has a warning which i dont understand the reason behind it:

  • abcdaf

    Hi, it seems like there are no errors in my code at all but when i try to run it, it shows some errors:

  • abcdaf

    Hi i got a question about Q2 and here it is(the question is on the code) :

  • abcdaf

    Hi, here is my solution for Q2 but i didnt understand a few things(the questions are in the code):

    • nascardriver

      The loop variable is a new variable. If it's not a reference, it's a copy of the current array element. Modifying a copy has no effect on the actual array.

  • Berrie

    To create the deck I've used the following loop:

    This way you don't need nested loops.
    Would one be preferred over the other, and why?

    Given the small number of iterations I don't think efficiency is a good argument. Personally I prefer this solution over nested loops for legibility but people that are not used to the mod operator might disagree.

  • J34NP3T3R

    need help. i forgot how to convert a CHAR into an INT of the same.

    for example ;

    char numRanks[]{ "23456789" };

    how do i return numRanks[3] ( which is "5" ) to an INTEGER value that will take it as ASCII value 5 not as ASCII number 53 ?

    if my function returns an INT type and i return numRanks[3] which is a CHAR the caller prints this as 53.

    i was able to do some research about using -48 as in numRanks[3] -48 which let the caller print 5 but is there a better way ?

  • J34NP3T3R

    is it ok if i use C-style strings

  • J34NP3T3R

    in Question #1 solution why did we use the scope resolution operator when we can access it using just max_items since its not an enum class ?
    can i use std::vector instead of std::array ?

    thanks guys

    • Tomek

      Put the enum in a namespace (for example "namespace ItemType") so that you can use the enum for indexing. I think the editor forgot to write a namespace... idk

  • kio

    Hi Nascardriver,
    Q3 and Q4,

    Nascardriver, do you use any extension for VisualStudion for c++?

Leave a Comment

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