Arrays are a foundational concept in C++ programming, allowing you to store a collection of items (typically of the same type) at contiguous memory locations. As you start with C++ or look to refresh your knowledge, this quiz will test your understanding of arrays in the language.
Try your hand at these ten multiple-choice questions, and check your answers below for explanations. Let’s jump in!
1. How do you declare an array of 5 integers in C++?
Answer:
Explanation:
Arrays in C++ are declared by specifying the type, followed by the array name and its size in square brackets.
2. Which index refers to the first element of an array?
Answer:
Explanation:
In C++, array indices start at 0. So, the first element of an array is accessed using index 0.
3. What is the size of an array int arr[10];?
Answer:
Explanation:
Each int typically occupies 4 bytes. Therefore, an array of 10 integers will occupy 10 x 4 = 40 bytes.
4. How do you determine the number of elements in an array named data?
Answer:
Explanation:
To get the number of elements, you divide the total size of the array by the size of a single element.
5. What will be the value of arr[2] after the following code is executed?
int arr[5] = {10, 20};
Answer:
Explanation:
If an array is initialized with fewer values than its size, the remaining elements get automatically initialized to zero.
6. Which of the following is NOT a correct way to initialize an array?
Answer:
Explanation:
Arrays are initialized using curly braces { }, not parentheses ( ).
7. Which of the following will give a compilation error?
Answer:
Explanation:
You cannot declare an array of size 0, a negative size, or without a size if it’s not being initialized immediately.
8. What happens if you try to access an array element using an index that is out of bounds?
Answer:
Explanation:
Accessing an element out of bounds does not cause a compilation error in C++, but it results in undefined behavior, which could be anything, including a crash or incorrect results.
9. Which of the following is a two-dimensional array?
Answer:
Explanation:
A two-dimensional array is essentially an “array of arrays”. It’s represented by rows and columns, as in option b.