WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Basic · question 11 of 100

How do you declare a single-dimensional array in C++? How do you access its elements?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

In C++, an array is a collection of elements of the same data type that are stored in contiguous memory locations. A single-dimensional array is an array with only one dimension, such as an array of integers or an array of characters. To declare a single-dimensional array in C++, you need to specify the data type of the elements, the array name, and the size of the array. Here’s an example of how to declare an array of integers with size 5:

    int myArray[5];

This declares an array called myArray that can hold 5 integers.

To access the elements of an array, you use square brackets [] with the index number of the element. The index number starts from 0 for the first element and goes up to the size of the array minus one for the last element. For example:

    myArray[0] = 1; // set the first element to 1
    myArray[1] = 2; // set the second element to 2
    int x = myArray[2]; // get the value of the third element

In this example, the first line sets the value of the first element of myArray to 1. The second line sets the value of the second element of myArray to 2. The third line gets the value of the third element of myArray and assigns it to a variable called x.

You can also use a for loop to iterate over the elements of an array and perform some operation on each element. For example:

    for (int i = 0; i < 5; i++) {
        myArray[i] = i * 2; // set each element to twice its index
    }

In this example, the for loop iterates over the elements of myArray and sets each element to twice its index.

In summary, to declare a single-dimensional array in C++, you need to specify the data type of the elements, the array name, and the size of the array. To access the elements of an array, you use square brackets [] with the index number of the element. You can use a for loop to iterate over the elements of an array and perform some operation on each element.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics