Arrays: Declaration, Indexing and Usage

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What is the index of the first element in a C++ array?

  • It is randomly assigned
  • 1
  • It depends on the data type
  • 0 (correct)

If myArray is an array, which of the following is the correct way to access the element at index 5?

  • myArray(5)
  • myArray[5] (correct)
  • myArray.5
  • myArray{5}

Which of the following is a correct way to declare an array of 10 integers named numbers?

  • int numbers(10);
  • int numbers{10};
  • int numbers = [10];
  • int numbers[10]; (correct)

What happens in C++ if you try to access an array element with an index that is out of bounds?

<p>The program may crash or produce unexpected results. (D)</p>
Signup and view all the answers

Given the array int arr[] = {5, 10, 15};, what is the value of arr[1]?

<p>10 (B)</p>
Signup and view all the answers

How can you initialize all elements of an integer array to zero during declaration?

<p>int arr[10] = {0}; (B)</p>
Signup and view all the answers

Which of the following is the correct way to declare a constant integer array named sizes of size 5?

<p>const int sizes[] = {10, 20, 30, 40, 50}; (C)</p>
Signup and view all the answers

What is the purpose of a null terminator in a C-string?

<p>It marks the end of the string. (B)</p>
Signup and view all the answers

Which of the following functions can be used to determine the length of a C-string?

<p>strlen() (C)</p>
Signup and view all the answers

Which header file should be included to use functions like strlen() and strcpy()?

<p><code>cstring</code> (D)</p>
Signup and view all the answers

What will be the output of the following code?

char str[] = "Hello";
cout << str[2];

<p>l (B)</p>
Signup and view all the answers

Which function is used to copy one C-string to another?

<p>strcpy() (B)</p>
Signup and view all the answers

What is a potential risk when using strcpy()?

<p>It can cause a buffer overflow if the destination array is too small. (A)</p>
Signup and view all the answers

Which of the following is the correct way to read a line of text from the user into a C-string named input with a maximum size of 100 characters?

<p>cin.getline(input, 100); (A)</p>
Signup and view all the answers

What does the following code do?

int numbers[5] = {1, 2};

<p>It initializes the first two elements to 1 and 2, and the rest to 0. (D)</p>
Signup and view all the answers

Why is it generally better to pass the size of an array to a function along with the array itself?

<p>Because C++ does not automatically provide array size information to functions. (C)</p>
Signup and view all the answers

Which of the following is NOT a valid operation for processing arrays?

<p>Comparing two arrays using == operator. (A)</p>
Signup and view all the answers

What is the time complexity of linear search on an array of size n?

<p>O(n) (D)</p>
Signup and view all the answers

For binary search to work correctly, what condition must be met?

<p>The array must be sorted. (A)</p>
Signup and view all the answers

What is the return value of the linear search algorithm if the element is not found in the array?

<p>-1 (C)</p>
Signup and view all the answers

What is the time complexity of binary search in the worst-case scenario?

<p>$O(log n)$ (A)</p>
Signup and view all the answers

Which searching algorithm is generally more efficient for large, sorted arrays?

<p>Binary Search (B)</p>
Signup and view all the answers

In selection sort, how many swaps are performed in each pass?

<p>1 (A)</p>
Signup and view all the answers

What is the primary goal of the selection sort algorithm?

<p>To place each element in its correct sorted position. (D)</p>
Signup and view all the answers

What is the time complexity of selection sort in the worst case?

<p>$O(n^2)$ (A)</p>
Signup and view all the answers

Given the array int arr[] = {5, 2, 8, 1, 9};, what would be the order of elements after the first pass of selection sort?

<p>{1, 2, 8, 5, 9} (C)</p>
Signup and view all the answers

Which of the following is the correct way to initialize a character array with the string 'Hello'?

<p>char str[] = &quot;Hello&quot;; (C)</p>
Signup and view all the answers

What does the atoi() function do?

<p>Converts a string to an integer. (A)</p>
Signup and view all the answers

In C++, can you directly assign one array to another using the assignment operator (=)?

<p>No, it is not allowed. (B)</p>
Signup and view all the answers

Given the C-string char str[] = "C++Exam";, what will strlen(str) return?

<p>8 (A)</p>
Signup and view all the answers

Suppose you want to prevent a function from modifying an array passed to it. How can you achieve this?

<p>Both B and C. (C)</p>
Signup and view all the answers

What is the issue with the following code?

int arr[5];
arr = {1, 2, 3, 4, 5};

<p>Arrays cannot be initialized after declaration using this syntax. (C)</p>
Signup and view all the answers

Which of the following operations shuffles the elements of an array randomly?

<p>Random Shuffling (A)</p>
Signup and view all the answers

What is the purpose of the shown code?

double temp = myList[0];
for (int i = 1; i < SIZE; i++)
{
    myList[i - 1] = myList[i];
}
myList[SIZE - 1] = temp;

<p>It shifts the array elements to the left. (B)</p>
Signup and view all the answers

Consider the following code that initializes an array with random values:

const int SIZE = 100;
double myList[SIZE];
for (int i = 0; i < SIZE; i++)
{
    myList[i] = rand() % 100;
}

What range of values can elements of the array have?

<p>0 to 99 (A)</p>
Signup and view all the answers

What is wrong in the following code?

double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};

<p>Arrays cannot be initialized after declaration this way. (C)</p>
Signup and view all the answers

What does the following code snippet do?

int arr[] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; ++i)
{
    cout << "arr[" << i << "] = " << arr[i] << endl;
}

<p>It prints the index and corresponding value of each element in the array. (C)</p>
Signup and view all the answers

Consider the following code:

int arr[4];
for (int i = 0; i < 4; ++i)
{
    arr[i] = i + 1;
}

What is the value of arr[3] after the loop?

<p>4 (A)</p>
Signup and view all the answers

Consider the following code. What is the output?

const int SIZE = 10;
int myList[SIZE];
int total = 0;
for (int i = 0; i < SIZE; i++)
{
    total += myList[i];
}
cout << "The total is: " << total << endl;

<p>Some random number (D)</p>
Signup and view all the answers

Consider the following code. What is the output?

const int ARRAY_SIZE = 5;
int myList[] = {1, 6, 5, 6, 2};
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{
    if (myList[i] >= max)
    {
        max = myList[i];
        indexOfMax = i;
    }
}
cout << "index is: " << indexOfMax;

<p>3 (C)</p>
Signup and view all the answers

A programmer wants to reverse an array in C++. They use the following code:

void reverse(const int list[], int newList[], int size)
{
    for (int i = 0, j = size - 1; i < size; i++, j--)
    {
        newList[j] = list[i];
    }
}

What are the values of newList after the procedure call, given int[] list1 = {1, 2, 3, 4, 5, 6}?

<p>newList = {6, 5, 4, 3, 2, 1} (A)</p>
Signup and view all the answers

Why cant arrays be directly returned from functions?

<p>Because of how C++ handles memory allocation for arrays. (C)</p>
Signup and view all the answers

Flashcards

Array

A data structure representing a collection of the same data types.

Declaring an array

The data type of the elements the array will hold, followed by a variable name and the number of elements in square brackets.

Array Indices

Elements in the array are accessed using their index. Indices start at 0.

Indexed variable

Using the array's index to access its contents.

Signup and view all the flashcards

No Bound Checking

C++ performs no checks to ensure that accesing an array element is within the bounds of the array.

Signup and view all the flashcards

Array Initializers

Arrays can be declared, created and initialized all in one step.

Signup and view all the flashcards

Shorthand Notation

When you declare, create, and initialize an array all in one, you have to do it all on one line.

Signup and view all the flashcards

Implicit Size

When declaring/creating an array, C++ allows omitting the array size if using an initializer. C++ figures it out automatically.

Signup and view all the flashcards

Partial Initialization

C++ allows you to initialize a part of the array. Elements not initialized are set to zero.

Signup and view all the flashcards

Printing an array

Printing an array can only be acheived by printing each element in the array using a loop.

Signup and view all the flashcards

Copying arrays

Copy arrays by copying individual elements from one array to another using a loop structure.

Signup and view all the flashcards

Summing array elements

To sum all elements in an array, loop through array, add elements to a total.

Signup and view all the flashcards

Linear search

To search for an item in an array, each element is sequentially checked with the target item until a match is found or the whole array has been searched.

Signup and view all the flashcards

Binary search

Efficient search algorithm that works on sorted arrays. It repeatedly divides the search interval in half.

Signup and view all the flashcards

Binary search condition

The elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order.

Signup and view all the flashcards

Sorting

Sorting means arranging the elements of an array in a specific order, such as ascending or descending.

Signup and view all the flashcards

Selection sort

A simple sorting algorithm that repeatedly finds the minimum element from the unsorted part and puts it at the beginning.

Signup and view all the flashcards

C-Strings

Arrays of characters. They are terminated with a null character '\0'.

Signup and view all the flashcards

Null terminator

C++ adds the character '\0', called the null terminator, to indicate the end of the string.

Signup and view all the flashcards

Printing a character array

For a character array, it can be printed using one print statement.

Signup and view all the flashcards

cin.getline

cin.getline stops reading characters when the delimiter character is encountered or when the size - 1 number of characters are read.

Signup and view all the flashcards

strlen

Returns the length of the string, i.e., the number of the characters before the null terminator.

Signup and view all the flashcards

strcpy

Copies string s2 to string s1.

Signup and view all the flashcards

strcmp

Compares strings

Signup and view all the flashcards

atoi

Returns an int value for the string.

Signup and view all the flashcards

Study Notes

  • Arrays are data structures holding collections of the same data type.
  • Arrays address the opening problem of reading a hundred numbers, computing their average, and determining how many are above the average.

Declaring Array Variables

  • General syntax: datatype arrayRefVar[arraySize];
  • Example: double myList[10];
  • The array size must be a constant expression.
  • This code is illegal if size is a variable:
    • int size = 4;
    • double myList[size]; // Wrong
  • Use const int size = 4; for a valid constant size.
  • Array elements receive arbitrary initial values upon creation.

Indexed Variables

  • Array elements are accessed via an index, starting at 0.
  • Indices range from 0 to arraySize-1.
  • Element syntax: arrayName[index]
  • myList[9] refers to the last element of array myList.

Using Indexed Variables

  • Indexed variables behave like regular variables after an array is created.
  • Example: myList[2] = myList[0] + myList[1]; adds the values in myList[0] and myList[1] and assigns the sum to myList[2].

No Bound Checking

  • C++ performs no array boundary checks.
  • Accessing elements beyond the bounds (e.g., myList[-1] or myList[11]) does not trigger syntax errors.
  • Out-of-bounds access may cause memory access violations reported by the OS.

Array Initializers

  • Declaring, creating, and initializing in one step:
    • dataType arrayName[arraySize] = {value0, value1, ..., valuek};
  • Example: double myList[4] = {1.9, 2.9, 3.4, 3.5}; is equivalent to:
    • double myList[4];
    • myList[0] = 1.9;
    • myList[1] = 2.9;
    • myList[2] = 3.4;
    • myList[3] = 3.5;
  • You have to declare, create, and initialize the array all in one statement to use shorthand notation.
  • Splitting it would cause a syntax error.
  • Invalid:
    • double myList[4];
    • myList = {1.9, 2.9, 3.4, 3.5}; // ERROR!

Implicit Size

  • C++ allows omitting the array size when using an initializer.
  • Example: double myList[] = {1.9, 2.9, 3.4, 3.5};
  • C++ can deduce the size based on the initializer list.

Partial Initialization

  • It is possible to initialize only part of an array.
  • Example: double myList[4] = {1.9, 2.9};
  • The uninitialized elements are set to zero.
  • If an array is declared but not initialized, it contains "garbage" values.

Initializing Arrays with Random Values

  • The following loop initializes the array myList with random values between 0 and 99:
const int SIZE = 100;
double myList[SIZE];
for (int i = 0; i < SIZE; i++) {
    myList[i] = rand() % 100;
}

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Data Structures and Arrays Quiz
18 questions
Data Structures and Arrays Quiz
5 questions
Computer Science Chapter 5: Arrays
21 questions
Use Quizgecko on...
Browser
Browser