Arrays and Strings in C++: Complete Chapter 5 Notes for Exam

5.1 Introduction to Arrays

Welcome to Chapter 5, class! You have learned variables, operators, loops, and control statements. Now I want you to think about a practical problem. Suppose you need to store the marks of 100 students. How would you do it using what you have learned so far?

You would need to write something like this:

int mark1, mark2, mark3, mark4, mark5, ... mark100;

That is 100 separate variables! Imagine trying to find the average — you would need to write mark1 + mark2 + mark3 + ... + mark100. What if you need 1000 values? This approach is simply impossible. This is exactly why arrays were created.

An array is a collection of elements of the same data type, stored in contiguous (adjacent) memory locations. Instead of 100 separate variables, you declare one array and access each element using an index number. It is like a row of lockers — each locker has a number (index), and all lockers are in a straight line (contiguous memory).

WHAT AN ARRAY LOOKS LIKE IN MEMORYIf we declare: int marks[5] = {85, 70, 92, 78, 88};Memory addresses (example): 1000 1004 1008 1012 1016 +——+ +——+ +——+ +——+ +——+ Index: [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] Values: | 85 | | 70 | | 92 | | 78 | | 88 | +——+ +——+ +——+ +——+ +——+ ^ ^ ^ ^ ^ | | | | | marks[0] marks[1] marks[2] marks[3] marks[4]Key points: – All elements are same data type (int) – Stored in contiguous memory (addresses 1000, 1004, 1008…) – Each int takes 4 bytes, so addresses differ by 4 – Index starts at 0, NOT 1 – Last index is size – 1 = 4

5.2 Array Definition

An array is a data structure that stores a fixed-size sequential collection of elements of the same type. The key characteristics are:

  • Fixed size — once declared, the size cannot change during program execution.
  • Same data type — all elements must be of the same type (all int, all float, all char, etc.).
  • Contiguous memory — elements are stored next to each other in memory.
  • Zero-based indexing — the first element is at index 0, the second at index 1, and so on.

5.3 Types of Arrays

Arrays are classified based on the number of dimensions (subscripts) they use:

  1. One-Dimensional (1D) Array — has one subscript. Think of it as a single row or a list.
  2. Multi-Dimensional Array — has two or more subscripts. The most common is the Two-Dimensional (2D) array, which you can think of as a table with rows and columns.

5.3.1 One-Dimensional Array

This is the simplest form of an array. A 1D array is essentially a list of values, all of the same type, accessed by a single index.

Declaration of a 1D Array

The general syntax for declaring a one-dimensional array is:

data_type array_name[size];

Let me explain each part:

  • data_type — the type of each element (int, float, char, double, etc.)
  • array_name — a valid C++ identifier (follows the same rules as variable names)
  • size — the number of elements the array can hold. Must be a constant positive integer.
int marks[5];       // An array of 5 integers
float prices[10];   // An array of 10 floats
char name[20];      // An array of 20 characters
double scores[100]; // An array of 100 doubles

I want you to notice something important: when you write int marks[5];, you are telling the compiler to reserve space for 5 integers. But at this point, the array contains garbage values — whatever random data was in those memory locations. The array is NOT automatically filled with zeros!

Initialization of a 1D Array

Initialization means giving the array its initial values at the time of declaration. There are several ways to do this:

Method 1: Initialize all elements

int marks[5] = {85, 70, 92, 78, 88};

The values are placed inside curly braces { }, separated by commas. The first value (85) goes to index 0, the second (70) to index 1, and so on.

Method 2: Partial initialization

int marks[5] = {85, 70};

If you provide fewer values than the size, the remaining elements are automatically initialized to zero. So this array becomes: {85, 70, 0, 0, 0}.

Exam Tip: Partial initialization fills remaining elements with 0. But if you provide NO initialization at all (int marks[5];), ALL elements contain garbage values. The zero-filling only happens when you provide at least one value in the initializer list.

Method 3: Let the compiler determine the size

int marks[] = {85, 70, 92, 78, 88};

If you omit the size, the compiler counts the number of values and sets the size automatically. Here, the compiler creates an array of size 5. This is convenient but only works when you initialize at declaration.

Method 4: Initialize all to zero

int marks[5] = {0};  // All five elements are 0

Placing a single 0 in the initializer sets all elements to zero. This is a common shortcut.

Accessing Array Elements

You access individual elements using the array name followed by an index inside square brackets [ ]:

int marks[5] = {85, 70, 92, 78, 88};

cout << marks[0];   // Output: 85 (first element)
cout << marks[2];   // Output: 92 (third element)
cout << marks[4];   // Output: 88 (fifth element)

marks[1] = 75;        // Change the second element to 75
cout << marks[1];   // Output: 75

CRITICAL WARNING — Array Index Out of Bounds:

C++ does NOT check whether an index is valid. If your array has 5 elements (indices 0 to 4) and you access marks[5] or marks[10], the compiler will NOT stop you. Your program will access whatever memory happens to be at that location. This is called out-of-bounds access and it causes undefined behavior — the program might crash, produce garbage, or seem to work correctly while hiding a dangerous bug.

int marks[5] = {85, 70, 92, 78, 88};
cout << marks[5];   // DANGER! Index 5 does not exist!
cout << marks[-1];  // DANGER! Negative index!

Valid indices for size N are 0 to N-1. Always remember this!

Memory Calculation for Arrays

The total memory occupied by an array depends on the size and the data type:

Total bytes = $\text{number\_of\_elements} \times \text{sizeof(data\_type)}$ Example: int marks[5]; → Total = $5 \times 4 = 20$ bytesExample: float prices[10]; → Total = $10 \times 4 = 40$ bytesExample: char name[20]; → Total = $20 \times 1 = 20$ bytes
MEMORY LAYOUT OF int marks[5]Base address: 1000 Each int = 4 bytes+———+———+———+———+———+ | marks[0]| marks[1]| marks[2]| marks[3]| marks[4]| | 85 | 70 | 92 | 78 | 88 | +———+———+———+———+———+ 1000 1004 1008 1012 1016Address of marks[i] = base_address + (i × sizeof(int)) Address of marks[3] = 1000 + (3 × 4) = 1012

Worked Example 1: Read and Display Array Elements

#include <iostream>
using namespace std;

int main()
{
    int n, i;
    cout << "How many students? ";
    cin >> n;

    int marks[n];   // Declare array with user-defined size

    // Reading elements
    cout << "Enter " << n << marks:" << endl;
    for (i = 0; i < n; i++)
    {
        cin >> marks[i];
    }

    // Displaying elements
    cout << "\n--- Marks ---" << endl;
    for (i = 0; i < n; i++)
    {
        cout << "Student " << (i + 1) << ": " << marks[i] << endl;
    }

    return 0;
}

Notice how we use a for loop with i going from 0 to n-1. This is the standard pattern for accessing all elements of an array. The loop variable i serves as the index. We print (i + 1) for the student number because humans count from 1, but array indices start from 0.

Worked Example 2: Find the Sum and Average of Array Elements

#include <iostream>
using namespace std;

int main()
{
    int marks[5] = {85, 70, 92, 78, 88};
    int sum = 0;
    float average;

    for (int i = 0; i < 5; i++)
    {
        sum = sum + marks[i];
    }

    average = (float)sum / 5;

    cout << "Sum = " << sum << endl;
    cout << "Average = " << average << endl;

    return 0;
}
// Output: Sum = 413, Average = 82.6

Exam Tip — Cast to float: We use (float)sum / 5 to get a decimal average. If we wrote sum / 5, both operands are integers, so C++ would perform integer division. For sum=413, 413 / 5 = 82 (not 82.6). The cast ensures floating-point division. Alternatively, write sum / 5.0.

Average of array elements: $\text{avg} = \frac{\sum_{i=0}^{n-1} \text{arr}[i]}{n}$ Always cast to float before dividing: $\text{avg} = \frac{(\text{float})\text{sum}}{n}$

Worked Example 3: Find the Largest Element in an Array

#include <iostream>
using namespace std;

int main()
{
    int arr[5] = {34, 89, 12, 67, 45};
    int largest = arr[0];   // Assume first element is largest

    for (int i = 1; i < 5; i++)
    {
        if (arr[i] > largest)
        {
            largest = arr[i];
        }
    }

    cout << "Largest element = " << largest << endl;
    return 0;
}
// Output: Largest element = 89

Here is the logic: we assume the first element is the largest. Then we compare it with every other element. If we find a bigger one, we update our “largest” variable. After checking all elements, largest holds the maximum value.

Why do we start the loop from i = 1 and not i = 0? Because we already used arr[0] as the initial value of largest. Comparing it with itself would be pointless — it would always be “not greater than” itself. Starting from 1 saves one unnecessary comparison.

Worked Example 4: Search for an Element (Linear Search)

#include <iostream>
using namespace std;

int main()
{
    int arr[5] = {34, 89, 12, 67, 45};
    int key, found = -1;

    cout << "Enter element to search: ";
    cin >> key;

    for (int i = 0; i < 5; i++)
    {
        if (arr[i] == key)
        {
            found = i;
            break;
        }
    }

    if (found != -1)
        cout << key << " found at index " << found << endl;
    else
        cout << key << " not found in the array." << endl;

    return 0;
}

This is called linear search — we check each element one by one from the beginning. If we find the element, we store its index and break out of the loop. If we finish the loop without finding it, we report “not found”. We use found = -1 as a flag because -1 is not a valid array index.

Practice Questions — One-Dimensional Array Basics

Q1. What is the correct way to declare an array of 10 integers named scores?

A) int scores(10);
B) array int scores[10];
C) int scores[10];
D) integer scores[10];

Answer: C

The correct C++ syntax is data_type array_name[size];. So int scores[10]; is correct. Option A uses parentheses (function call syntax, wrong). Option B reverses the order (wrong). Option D uses integer which is not a C++ keyword (the correct keyword is int).

Q2. If int arr[6] = {10, 20, 30};, what is the value of arr[4]?

A) 30
B) 0
C) Garbage value
D) Error

Answer: B

When an array is partially initialized, all remaining elements are automatically set to zero. Here, only the first 3 elements are given values (10, 20, 30). Elements at indices 3, 4, and 5 are set to 0. So arr[4] = 0. This zero-filling only happens with partial initialization — if there were no initializer at all (int arr[6];), all elements would be garbage.

Q3 (Fill in the Blank). For an array declared as double data[8];, the valid index range is _________ to _________, and the total memory occupied is _________ bytes.

Answer: 0 to 7; 64

Valid indices always start at 0 and end at size-1. For size 8: indices 0, 1, 2, 3, 4, 5, 6, 7. Memory: 8 elements × 8 bytes per double = 64 bytes. Formula: total bytes = size × sizeof(data_type) = 8 × 8 = 64.

Advertisement

Array Manipulation Operations

Now let us look at common operations performed on arrays. These are very frequently tested in exams.

1. Inserting an Element

To insert an element at a specific position, you must first shift all elements from that position onward one position to the right to make space. Then place the new element.

#include <iostream>
using namespace std;

int main()
{
    int arr[6] = {10, 20, 30, 40, 50};  // size 6, currently 5 elements
    int n = 5;  // current number of elements
    int pos, value;

    cout << "Array: ";
    for (int i = 0; i < n; i++) cout << arr[i] << " ";

    cout << "\nEnter position to insert (0 to " << n << "): ";
    cin >> pos;
    cout << "Enter value: ";
    cin >< value;

    // Shift elements to the right
    for (int i = n; i > pos; i--)
    {
        arr[i] = arr[i - 1];
    }

    arr[pos] = value;  // Insert the new element
    n++;               // Increase element count

    cout << "After insertion: ";
    for (int i = 0; i < n; i++) cout << arr[i] << " ";

    return 0;
}

Notice the shifting loop goes backward — from n down to pos+1. Why? If we went forward, we would overwrite elements before we could shift them! By going backward, we safely move each element one position right. For example, to insert at position 2: arr[5]=arr[4], arr[4]=arr[3], arr[3]=arr[2], then arr[2]=new value. Each element is moved safely because we always read from a position that has not been overwritten yet.

See also  C++ Programming Fundamentals: Complete Chapter 3 Notes for Exam

2. Deleting an Element

To delete an element, you shift all elements after the deleted position one position to the left, overwriting the element to be deleted.

#include <iostream>
using namespace std;

int main()
{
    int arr[5] = {10, 20, 30, 40, 50};
    int n = 5;
    int pos;

    cout << "Array: ";
    for (int i = 0; i < n; i++) cout << arr[i] << " ";

    cout << "\nEnter position to delete (0 to " << (n-1) << "): ";
    cin >> pos;

    // Shift elements to the left
    for (int i = pos; i < n - 1; i++)
    {
        arr[i] = arr[i + 1];
    }
    n--;  // Decrease element count

    cout << "After deletion: ";
    for (int i = 0; i < n; i++) cout << arr[i] << " ";

    return 0;
}

For deletion, the shifting loop goes forward — from pos to n-2. Each element arr[i] is replaced by arr[i+1]. This overwrites the element at the deletion position and shifts everything left. After deletion, the logical size (n) decreases by 1, but the physical array size stays the same.

Exam Note — Insert vs Delete Shifting Direction:

  • Insert: Shift right → loop goes backward (from end to position)
  • Delete: Shift left → loop goes forward (from position to end)

This is a very common exam question — they often give you code with the wrong direction and ask what goes wrong!

Practice Questions — Array Manipulation

Q1. When inserting an element at position pos in an array, the loop that shifts elements should iterate:

A) From pos to n, going forward
B) From n down to pos+1, going backward
C) From 0 to pos, going forward
D) From pos to 0, going backward

Answer: B

When inserting, you shift elements to the RIGHT. To avoid overwriting data, you must start from the end and move backward: for (i = n; i > pos; i--) arr[i] = arr[i-1];. Going forward would overwrite arr[pos+1] with arr[pos] before you could save arr[pos+1]’s value. Think of it like moving people in a row to make room — you start from the far end and ask each person to move one seat right.

Q2. What is the time complexity of linear search in an array of n elements in the worst case?

A) O(1)
B) O(log n)
C) O(n)
D) O(n²)

Answer: C

In the worst case of linear search, the element is either at the last position or not in the array at all. In both cases, you must check all n elements. So the worst-case time complexity is O(n) — it grows linearly with the number of elements. Best case is O(1) when the element is at the first position. Average case is also O(n/2) which simplifies to O(n).

Advertisement

5.3.2 Multi-Dimensional Arrays

Sometimes data has more than one dimension. Think of a spreadsheet — it has rows AND columns. A chessboard has 8 rows and 8 columns. A classroom seating arrangement has rows and columns. For such data, we need multi-dimensional arrays.

A two-dimensional (2D) array is the most common type. You can think of it as an array of arrays — each element of the outer array is itself an array (a row).

Declaration of a 2D Array

data_type array_name[rows][columns];
int matrix[3][4];    // 3 rows, 4 columns = 12 integers
float table[2][3];   // 2 rows, 3 columns = 6 floats

Initialization of a 2D Array

// Method 1: Full initialization with nested braces
int matrix[2][3] = {
    {1, 2, 3},    // Row 0
    {4, 5, 6}     // Row 1
};

// Method 2: Without nested braces (filled row by row)
int matrix[2][3] = {1, 2, 3, 4, 5, 6};

// Method 3: Partial initialization
int matrix[2][3] = {{1, 2}, {4}};  // Becomes {{1, 2, 0}, {4, 0, 0}}

Accessing Elements of a 2D Array

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

cout << matrix[0][0];   // Output: 1 (Row 0, Column 0)
cout << matrix[0][2];   // Output: 3 (Row 0, Column 2)
cout << matrix[1][1];   // Output: 5 (Row 1, Column 1)

matrix[1][2] = 99;       // Change element at Row 1, Column 2

The first index is always the row, and the second is always the column: array[row][column].

TWO-DIMENSIONAL ARRAY IN MEMORYDeclaration: int matrix[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};Logical view (rows and columns):Col 0 Col 1 Col 2 Col 3 +——-+——-+——-+——-+ Row 0 | 1 | 2 | 3 | 4 | +——-+——-+——-+——-+ Row 1 | 5 | 6 | 7 | 8 | +——-+——-+——-+——-+ Row 2 | 9 | 10 | 11 | 12 | +——-+——-+——-+——-+Memory view (stored row by row — contiguous): +—-+—-+—-+—-+—-+—-+—-+—-+—-+—-+—-+—-+ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | +—-+—-+—-+—-+—-+—-+—-+—-+—-+—-+—-+—-+ [0][0] [0][1] [0][2] [0][3] [1][0] [1][1] [1][2] [1][3] [2][0] …C++ stores 2D arrays in row-major order: Row 0 elements first, then Row 1, then Row 2.
Total elements in a 2D array = $\text{rows} \times \text{columns}$ Total memory = $\text{rows} \times \text{columns} \times \text{sizeof(data\_type)}$ For int matrix[3][4]: $3 \times 4 \times 4 = 48$ bytesAddress of element [i][j] = base + $(i \times \text{cols} + j) \times \text{sizeof(type)}$

Worked Example 5: Read and Display a 2D Array

#include <iostream>
using namespace std;

int main()
{
    int matrix[2][3];
    int i, j;

    // Reading elements
    cout << "Enter 6 elements (2 rows x 3 columns):" << endl;
    for (i = 0; i < 2; i++)        // outer loop: rows
    {
        for (j = 0; j < 3; j++)    // inner loop: columns
        {
            cin >> matrix[i][j];
        }
    }

    // Displaying elements
    cout << "\nMatrix:" << endl;
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 3; j++)
        {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;  // new line after each row
    }

    return 0;
}

See the pattern? We always use nested loops for 2D arrays. The outer loop handles rows, the inner loop handles columns. After the inner loop finishes (all columns of one row are printed), we use endl to move to the next line before the next row starts. This tab-separated format creates a neat table-like output.

Worked Example 6: Sum of All Elements in a 2D Array

#include <iostream>
using namespace std;

int main()
{
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int sum = 0;

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            sum += matrix[i][j];
        }
    }

    cout << "Sum of all elements = " << sum << endl;
    return 0;
}
// Output: Sum of all elements = 45

Worked Example 7: Sum of Diagonal Elements

#include <iostream>
using namespace std;

int main()
{
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int diagSum = 0;

    for (int i = 0; i < 3; i++)
    {
        diagSum += matrix[i][i];  // i == j for main diagonal
    }

    cout << "Main diagonal sum = " << diagSum << endl;
    return 0;
}
// Output: Main diagonal sum = 15 (1 + 5 + 9)

The main diagonal (also called principal diagonal) consists of elements where the row index equals the column index: [0][0], [1][1], [2][2]. For a square matrix (rows = columns), you only need one loop because i == j.

Exam Tip — Diagonal Elements: For the main diagonal of an n×n matrix, elements are at positions where row = column: matrix[i][i]. For the anti-diagonal (secondary diagonal), elements are at positions where row + column = n – 1: matrix[i][n-1-i]. For a 3×3 matrix, anti-diagonal elements are [0][2], [1][1], [2][0]. Exams often ask for both.

Practice Questions — Two-Dimensional Arrays

Q1. How many bytes does int table[4][5]; occupy in memory?

A) 20
B) 40
C) 80
D) 9

Answer: C

Total bytes = rows × columns × sizeof(int) = 4 × 5 × 4 = 80 bytes. There are 20 total elements (4×5), and each integer takes 4 bytes. Option A (20) is the number of elements, not bytes. Option B (40) would be correct if each element were 2 bytes (like short int). Option D (9) is meaningless here.

Q2. In a 2D array int arr[3][4], what is the row and column of element arr[2][3]?

A) Row 2, Column 3 (3rd row, 4th column)
B) Row 3, Column 4
C) Row 1, Column 2
D) It is out of bounds

Answer: A

arr[2][3] means Row index 2, Column index 3. Since indexing starts at 0, this is the 3rd row and 4th column. Valid row indices are 0, 1, 2 (for 3 rows), and valid column indices are 0, 1, 2, 3 (for 4 columns). So [2][3] IS valid — it is the last element. Option B is wrong because it uses 1-based counting (not how C++ works). Option D is wrong because [2][3] is within bounds.

Q3. What is the output of the following code?

int m[2][2] = {{1, 2}, {3, 4}};
cout << m[0][1] + m[1][0];
A) 3
B) 4
C) 5
D) 7

Answer: C

m[0][1] is Row 0, Column 1 = 2. m[1][0] is Row 1, Column 0 = 3. So 2 + 3 = 5. This tests whether you can correctly identify elements in a 2D array from the initializer list. Row 0 is {1, 2} and Row 1 is {3, 4}.

Advertisement

5.3 String

5.3.1 String Definition

A string is a sequence of characters. In C++, there are two ways to work with strings:

  1. C-style strings — arrays of characters terminated by a null character '\0'. This is the traditional C approach.
  2. C++ string class — using the #include <string> library. This is the modern, easier approach.

In this course (following your module), we focus on C-style strings because they help you understand how strings work at the memory level. A C-style string is simply a character array where the last character is always a special null character '\0' (ASCII value 0) that marks the end of the string.

HOW A C-STYLE STRING IS STOREDDeclaration: char name[6] = “Hello”;+——–+——–+——–+——–+——–+——–+ | ‘H’ | ‘e’ | ‘l’ | ‘l’ | ‘o’ | ‘\0’ | +——–+——–+——–+——–+——–+——–+ name[0] name[1] name[2] name[3] name[4] name[5] 72 101 108 108 111 0Key points: – “Hello” has 5 characters but the array size is 6 – The extra space is for the null terminator ‘\0’ – ‘\0’ tells C++ where the string ends – Without ‘\0’, functions like cout would keep reading past the string into garbage memory! – Size rule: array size >= string length + 1

The +1 Rule for Strings: If your string has n characters, you need an array of at least n+1 elements to store it. The '\0' takes one extra position. Forgetting this is a very common error:

char str[5] = "Hello";  // WRONG! "Hello" needs 6 slots (5 chars + '\0')
char str[6] = "Hello";  // CORRECT
char str[] = "Hello";   // CORRECT — compiler auto-sizes to 6

5.3.2 String Declaration and Initialization

Method 1: Character by character

char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'};  // Must include '\0' manually!

Method 2: Using a string literal (recommended)

char name[6] = "Hello";    // Compiler automatically adds '\0'
char name[] = "Hello";     // Compiler sets size to 6 automatically

When you use double quotes "...", the compiler automatically appends the null terminator. This is much easier and less error-prone than Method 1.

Method 3: Declaration without initialization

char name[20];  // Declares space for 19 characters + '\0'
// Must be filled later using cin or assignment

Reading and Displaying Strings

#include <iostream>
using namespace std;

int main()
{
    char name[50];

    // Method 1: cin >> (reads only one word, stops at space)
    cout << "Enter your first name: ";
    cin >> name;
    cout << "Hello, " << name << endl;

    // Method 2: cin.getline() (reads entire line including spaces)
    char fullName[50];
    cout << "Enter your full name: ";
    cin.getline(fullName, 50);
    cout << "Hello, " << fullName << endl;

    return 0;
}

CRITICAL: cin >> vs cin.getline()

  • cin >> name reads only one word — it stops at the first whitespace (space, tab, newline). If you type “Abebe Kebede”, only “Abebe” is stored.
  • cin.getline(name, size) reads the entire line including spaces, up to size-1 characters. It stops when it encounters a newline or when size-1 characters have been read.

Use cin >> for single words (names, cities). Use cin.getline() for sentences or names with spaces.

Exam Tip — Mixing cin >> and cin.getline(): If you use cin >> variable before cin.getline(), the getline will read the leftover newline from cin and appear to be “skipped.” Fix it by adding cin.ignore() before getline:

int age;
cin >> age;
cin.ignore();              // Clear the leftover newline
char name[50];
cin.getline(name, 50);    // Now works correctly

5.3.3 String Manipulation

C++ provides several useful functions for working with C-style strings in the <cstring> library. Let me explain each one with examples.

1. strlen() — String Length

Returns the number of characters in the string (NOT including the null terminator).

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[] = "Hello";
    cout << "Length: " << strlen(str);  // Output: 5
    return 0;
}

Note: The string “Hello” has 5 characters. strlen does NOT count '\0'. The array size is 6, but the string length is 5.

2. strcpy() — Copy String

Copies the content of one string into another. The destination must be large enough.

char src[] = "Hello";
char dest[10];

strcpy(dest, src);   // dest now contains "Hello"
cout << dest;        // Output: Hello

// DANGER: Destination too small
char small[3];
strcpy(small, "Hello");  // Buffer overflow! "Hello" needs 6 chars

3. strcat() — Concatenate (Join) Strings

Appends one string to the end of another. The destination must have enough space for the combined string.

char first[20] = "Hello";
char second[] = " World";

strcat(first, second);   // first becomes "Hello World"
cout << first;           // Output: Hello World
Required destination size for strcat: $\text{len(dest)} + \text{len(src)} + 1$ For “Hello” + ” World”: $5 + 6 + 1 = 12$ bytes minimum

4. strcmp() — Compare Strings

Compares two strings character by character based on ASCII values. Returns:

  • 0 — if both strings are identical
  • Negative value — if the first string is “less than” the second (comes earlier alphabetically)
  • Positive value — if the first string is “greater than” the second
char s1[] = "Apple";
char s2[] = "Banana";
char s3[] = "Apple";

cout << strcmp(s1, s2);   // Negative (A < B in ASCII)
cout << strcmp(s2, s1);   // Positive (B > A in ASCII)
cout << strcmp(s1, s3);   // 0 (identical)

// Common usage in if-statements:
if (strcmp(s1, s3) == 0)
    cout << "Strings are equal";

CRITICAL: You CANNOT compare strings with ==!

char s1[] = "Hello";
char s2[] = "Hello";

if (s1 == s2)       // WRONG! Compares addresses, not content
    cout << "Equal";

if (strcmp(s1, s2) == 0)   // CORRECT! Compares content
    cout << "Equal";

The == operator on C-style strings compares the memory addresses of the two arrays, not their content. Even if both contain “Hello”, they are stored at different addresses, so == would return false. Always use strcmp() for string comparison!

5. strrev() — Reverse a String

char str[] = "Hello";
strrev(str);
cout << str;   // Output: olleH

6. strupr() and strlwr() — Convert Case

char str[] = "Hello World";
strupr(str);   cout << str;   // Output: HELLO WORLD
strlwr(str);   cout << str;   // Output: hello world

Summary of String Functions (<cstring>):

FunctionPurposeExampleResult
strlen(s)String lengthstrlen("Hi")2
strcpy(d, s)Copy s to dstrcpy(d, "Hi")d = “Hi”
strcat(d, s)Append s to dstrcat("Hi ", "there")“Hi there”
strcmp(s1, s2)Compare stringsstrcmp("A", "B")Negative
strrev(s)Reverse stringstrrev("Hi")“iH”
strupr(s)Convert to uppercasestrupr("hi")“HI”
strlwr(s)Convert to lowercasestrlwr("HI")“hi”

Worked Example 8: Count Vowels in a String

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[100];
    int vowels = 0, i;

    cout << "Enter a string: ";
    cin.getline(str, 100);

    for (i = 0; str[i] != '\0'; i++)
    {
        if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
            str[i] == 'o' || str[i] == 'u' ||
            str[i] == 'A' || str[i] == 'E' || str[i] == 'I' ||
            str[i] == 'O' || str[i] == 'U')
        {
            vowels++;
        }
    }

    cout << "Number of vowels: " << vowels << endl;
    return 0;
}

Notice the loop condition: str[i] != '\0'. This is the standard way to iterate through a C-style string — you keep going until you hit the null terminator. You do NOT need to know the length beforehand. The '\0' acts as the stop sign. This is why the null terminator is so important — without it, the loop would keep reading into garbage memory!

Worked Example 9: Check if a String is a Palindrome

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[50];
    int len, i, isPalindrome = 1;

    cout << "Enter a string: ";
    cin >> str;

    len = strlen(str);

    for (i = 0; i < len / 2; i++)
    {
        if (str[i] != str[len - 1 - i])
        {
            isPalindrome = 0;
            break;
        }
    }

    if (isPalindrome)
        cout << "Palindrome!" << endl;
    else
        cout << "Not a palindrome." << endl;

    return 0;
}

A palindrome reads the same forward and backward (like “madam” or “racecar”). The logic: compare the first character with the last, the second with the second-last, and so on. We only need to check up to the middle (len / 2). If any pair does not match, it is not a palindrome.

Palindrome check: For each $i$ from $0$ to $\lfloor \frac{\text{len}}{2} \rfloor – 1$, check if $\text{str}[i] = \text{str}[\text{len} – 1 – i]$.

Practice Questions — Strings

Q1. What is the output of cout << strlen("Hello World");?

A) 11
B) 12
C) 10
D) 13

Answer: A

strlen counts all characters EXCEPT the null terminator. “Hello World” has: H-e-l-l-o-(space)-W-o-r-l-d = 11 characters. The space between Hello and World IS counted as a character. The null terminator '\0' is NOT counted. So the answer is 11, not 12.

Q2. Which of the following correctly compares two C-style strings s1 and s2 for equality?

A) if (s1 == s2)
B) if (strcmp(s1, s2))
C) if (strcmp(s1, s2) == 0)
D) if (strcmp(s1, s2) == 1)

Answer: C

strcmp() returns 0 when the strings are equal. So the correct condition is strcmp(s1, s2) == 0. Option A is wrong because == compares addresses, not content. Option B is wrong because strcmp(s1, s2) is truthy (non-zero) when strings are DIFFERENT — it would enter the if block for unequal strings. Option D is wrong because strcmp returns 0 for equality, not 1.

Q3. What happens if you declare char str[5] = "Hello";?

A) str contains “Hello” correctly
B) The compiler automatically increases the array size to 6
C) The null terminator ‘\0’ overflows into adjacent memory (buffer overflow)
D) Compilation error

Answer: C

“Hello” has 5 characters plus the null terminator = 6 bytes needed. But the array only has 5 bytes. The compiler does NOT automatically resize the array (option B is wrong — that only happens when you omit the size entirely). Instead, the '\0' gets written into the memory location right after the array, which is a buffer overflow. This is undefined behavior — it might seem to work, or it might corrupt other variables, or it might crash. There is NO compilation error (option D is wrong) because the syntax is valid — it is a runtime logical error.

Advertisement

Chapter Summary — Key Points to Remember

  • An array is a collection of same-type elements stored in contiguous memory.
  • Array index starts at 0. Valid indices: 0 to size-1.
  • Partial initialization fills remaining elements with 0. No initialization = garbage values.
  • C++ does NOT check array bounds — out-of-bounds access is undefined behavior.
  • For insertion: shift elements right (loop backward). For deletion: shift left (loop forward).
  • 2D arrays are stored in row-major order. Use nested loops: outer = rows, inner = columns.
  • C-style strings are char arrays ending with '\0'. Array size >= string length + 1.
  • Use cin >> for single words, cin.getline() for full lines.
  • Use strcmp() to compare strings — NEVER use ==.
  • Use strcpy() to copy strings — NEVER use =.
  • Iterate through strings using: for (i = 0; str[i] != '\0'; i++).

Quick Revision Notes — Exam Focus

1D Array — Essential Facts

  • Declaration: data_type name[size];
  • Index range: 0 to size-1
  • Memory: size × sizeof(data_type) bytes
  • Partial init: int a[5] = {1, 2};{1, 2, 0, 0, 0}
  • Full zero init: int a[5] = {0};
  • No init: all garbage values
  • Auto-size: int a[] = {1, 2, 3}; → size = 3
  • Out-of-bounds: NO compiler check, undefined behavior

2D Array — Essential Facts

  • Declaration: data_type name[rows][cols];
  • Total elements: rows × columns
  • Memory: rows × cols × sizeof(data_type) bytes
  • Stored in row-major order
  • Access: name[row][col] — row FIRST, then column
  • Always use nested loops: outer = rows, inner = columns
  • Main diagonal: elements where i == j
  • Anti-diagonal: elements where i + j == n - 1

C-Style Strings — Essential Facts

  • A string is a char array ending with '\0'
  • Size rule: array_size ≥ string_length + 1
  • Init: char s[6] = "Hello"; (compiler adds ‘\0’)
  • cin >> s: reads one word (stops at space)
  • cin.getline(s, n): reads full line (up to n-1 chars)
  • Never use == to compare — use strcmp(s1, s2) == 0
  • Never use = to copy — use strcpy(dest, src)
  • Iterate: for (i = 0; s[i] != '\0'; i++)
  • After cin >> before getline(): use cin.ignore()

String Functions Quick Reference (<cstring>)

FunctionPurposeReturns
strlen(s)Length of sInteger (excludes ‘\0’)
strcpy(d, s)Copy s to dPointer to d
strcat(d, s)Append s to dPointer to d
strcmp(s1, s2)Compare s1 and s20 if equal, negative if s1<s2, positive if s1>s2
strrev(s)Reverse sPointer to s
strupr(s)UppercasePointer to s
strlwr(s)LowercasePointer to s

Key Formulas

  • Array memory: $\text{bytes} = n \times \text{sizeof(type)}$
  • 2D memory: $\text{bytes} = R \times C \times \text{sizeof(type)}$
  • Address of arr[i]: $\text{base} + i \times \text{sizeof(type)}$
  • Address of arr[i][j]: $\text{base} + (i \times C + j) \times \text{sizeof(type)}$
  • strcat dest size: $\text{len}(d) + \text{len}(s) + 1$
  • Palindrome check: compare $\text{str}[i]$ with $\text{str}[n-1-i]$ for $i = 0$ to $\lfloor n/2 \rfloor – 1$

Common Mistakes to Avoid

  • ❌ Accessing arr[size] — valid indices are 0 to size-1
  • char s[5] = "Hello"; — needs 6 bytes (forgetting ‘\0’)
  • ❌ Comparing strings with == — use strcmp()
  • ❌ Copying strings with = — use strcpy()
  • ❌ Using cin >> for strings with spaces — use cin.getline()
  • ❌ Forgetting cin.ignore() between cin >> and getline()
  • ❌ Insert shift loop going forward — should go backward
  • ❌ Delete shift loop going backward — should go forward
  • ❌ Using wrong index order for 2D: arr[col][row] — should be arr[row][col]
  • ❌ Forgetting to include <cstring> for string functions

Important Definitions

  • Array: A collection of same-type elements stored in contiguous memory locations, accessed by index.
  • Index: The position number used to access an element. Starts at 0 in C++.
  • Contiguous memory: Memory locations that are adjacent to each other with no gaps.
  • String: A sequence of characters terminated by a null character (‘\0’).
  • Null terminator (‘\0’): A character with ASCII value 0 that marks the end of a C-style string.
  • Buffer overflow: Writing data beyond the allocated memory of an array — undefined behavior.
  • Row-major order: Storing 2D array elements row by row in linear memory.
  • Palindrome: A string that reads the same forward and backward.

Challenge Exam Questions — Test Yourself!

Q1 (MCQ — Hard)

What is the output of the following code?

int arr[] = {5, 10, 15, 20, 25};
int s = 0;
for (int i = 1; i < 4; i++)
    s += arr[i];
cout << s;
A) 75
B) 45
C) 50
D) 30

Answer: B

The loop runs from i=1 to i=3 (not 0 to 4!). So it accesses arr[1]=10, arr[2]=15, arr[3]=20. Sum = 10 + 15 + 20 = 45. It skips arr[0]=5 and arr[4]=25. This tests whether you carefully read the loop bounds. Many students assume loops always start at 0 and go to the end — but here the range is deliberately restricted.

Q2 (MCQ — Hard)

What is the value of arr[2] after execution?

int arr[5] = {1, 2, 3, 4, 5};
arr[0] = arr[0] + arr[4];
arr[4] = arr[1] + arr[3];
arr[2] = arr[0] - arr[4];
A) 3
B) -4
C) 0
D) 6

Answer: B

Step 1: arr[0] = 1 + 5 = 6. Step 2: arr[4] = 2 + 4 = 6. Step 3: arr[2] = 6 - 6 = 0. Wait — that gives 0 (option C). But note: at step 2, arr[1] is still 2 and arr[3] is still 4 (they were not modified). So arr[4] = 2 + 4 = 6. Then arr[2] = arr[0] – arr[4] = 6 – 6 = 0. The answer is 0. (Note: if you miscalculated arr[4] using the new arr[0]=6 somehow, you might get wrong answers. The key is that arr[1] and arr[3] are unchanged.)

Q3 (Fill in the Blank — Hard)

The address of element matrix[2][3] in a 2D array with base address 1000, where each element is 4 bytes and the array has 5 columns, is _________.

Answer: 1060

Formula: Address = base + $(i \times \text{cols} + j) \times \text{sizeof(type)}$

Address = $1000 + (2 \times 5 + 3) \times 4 = 1000 + 13 \times 4 = 1000 + 52 = 1052$. Wait, let me recalculate: $1000 + (2 \times 5 + 3) \times 4 = 1000 + (10 + 3) \times 4 = 1000 + 52 = 1052$. The answer is 1052. The position in row-major order is: skip 2 full rows (2 × 5 = 10 elements), then 3 more columns = 13 elements from the start. 13 × 4 bytes = 52 bytes from base.

Q4 (True/False — Hard)

In C++, the statement char s1[10] = "Hello", s2[10] = "Hello"; if (s1 == s2) cout << "Equal"; will print "Equal".

Answer: False

The == operator on C-style character arrays compares the memory addresses of the two arrays, NOT their content. Since s1 and s2 are two different arrays stored at different memory locations, s1 == s2 is false, even though both contain "Hello". To compare string content, you must use if (strcmp(s1, s2) == 0). This is one of the most commonly tested concepts about strings.

Q5 (MCQ — Hard)

What is the output?

char str[] = "programming";
int count = 0;
for (int i = 0; str[i] != '\0'; i++)
{
    if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
        str[i] == 'o' || str[i] == 'u')
        count++;
}
cout << count;
A) 2
B) 3
C) 4
D) 5

Q6 (MCQ — Hard)

After the following code executes, what is the content of result?

char s1[20] = "Good";
char s2[] = "Morning";
char result[20];
strcpy(result, s1);
strcat(result, " ");
strcat(result, s2);
A) "Good Morning"
B) "GoodMorning"
C) "Good Morning " (with trailing space)
D) Error

Answer: A

Step 1: strcpy(result, s1) → result = "Good". Step 2: strcat(result, " ") → result = "Good ". Step 3: strcat(result, s2) → result = "Good Morning". The space is added between the words by concatenating a literal space string " " in between. Result = "Good Morning". The result array needs at least 13 bytes (12 characters + '\0'), and it has 20, so no overflow.

Q7 (Short Answer — Hard)

Write a C++ program that finds the second largest element in a 1D array of integers.

#include <iostream>
using namespace std;

int main()
{
    int arr[6] = {34, 89, 12, 89, 67, 45};
    int n = 6;
    int largest = arr[0], secondLargest = -99999;

    for (int i = 1; i < n; i++)
    {
        if (arr[i] > largest)
        {
            secondLargest = largest;
            largest = arr[i];
        }
        else if (arr[i] > secondLargest && arr[i] != largest)
        {
            secondLargest = arr[i];
        }
    }

    if (secondLargest == -99999)
        cout << "No second largest element." << endl;
    else
        cout << "Second largest: " << secondLargest << endl;

    return 0;
}
// Output: Second largest: 67

Explanation: The logic tracks both the largest and second-largest as we scan the array. When we find a new largest, the old largest becomes the second-largest. When we find a value between second-largest and largest (but not equal to largest), it becomes the new second-largest. The arr[i] != largest check handles duplicate maximum values (like 89 appearing twice). The answer is 67.

Q8 (MCQ — Hard)

What is the output?

int arr[5] = {10, 20, 30, 40, 50};
int i;
for (i = 0; i < 5; i++)
    cout << arr[i] * 2 << " ";
cout << endl << arr[2];
A) 20 40 60 80 100 followed by 30
B) 20 40 60 80 100 followed by 60
C) 10 20 30 40 50 followed by 30
D) 20 40 60 80 100 followed by 30

Answer: D

The loop prints each element multiplied by 2: 20, 40, 60, 80, 100. Then arr[2] prints the ORIGINAL value at index 2, which is 30 (the multiplication in the cout does NOT modify the array — arr[i] * 2 is just a calculation, not an assignment). The array is unchanged after the loop. If the code had been arr[i] = arr[i] * 2;, then arr[2] would be 60. But since it only prints the calculation, the array stays {10, 20, 30, 40, 50}.

Q9 (Write a Program — Hard)

Write a C++ program that reads a 3×3 matrix from the user and displays the sum of each row.

#include <iostream>
using namespace std;

int main()
{
    int matrix[3][3];
    int i, j, rowSum;

    cout << "Enter 9 elements for 3x3 matrix:" << endl;
    for (i = 0; i < 3; i++)
        for (j = 0; j < 3; j++)
            cin >> matrix[i][j];

    cout << "\nRow sums:" << endl;
    for (i = 0; i < 3; i++)
    {
        rowSum = 0;
        for (j = 0; j < 3; j++)
        {
            rowSum += matrix[i][j];
        }
        cout << "Row " << (i + 1) << " sum = " << rowSum << endl;
    }

    return 0;
}

Explanation: We use nested loops. The outer loop iterates over each row. Before processing each row, we reset rowSum to 0. The inner loop adds all column values of that row. After the inner loop completes, we print the sum for that row. The key is resetting rowSum inside the outer loop (before the inner loop) so each row starts with a fresh sum of 0.

Q10 (MCQ — Hard)

What is the output?

char s1[] = "abc";
char s2[] = "abd";
cout << strcmp(s1, s2);
A) 0
B) A positive number
C) A negative number
D) Error

Answer: C

strcmp compares character by character using ASCII values. First two characters match ('a' == 'a', 'b' == 'b'). At position 2: 'c' (ASCII 99) vs 'd' (ASCII 100). Since 99 < 100, "abc" is "less than" "abd", so strcmp returns a negative number. The exact value depends on the implementation (could be -1 or the ASCII difference), but it is always negative. If the first string were greater, the result would be positive. If identical, exactly 0.

Q11 (Fill in the Blank — Hard)

To read a sentence with spaces from the user into a character array str of size 100, you would use _________(str, _________);.

Answer: cin.getline; 100

The correct call is cin.getline(str, 100);. The first argument is the character array name, and the second is the maximum number of characters to read (including the null terminator). It reads up to 99 characters and adds ‘\0’, or stops at a newline, whichever comes first. This is the standard way to read strings with spaces in C++.

Q12 (True/False — Hard)

The statement int arr[]; is a valid array declaration in C++.

Answer: False

When you declare an array without specifying the size, you MUST provide an initializer so the compiler can determine the size from the number of values: int arr[] = {1, 2, 3}; is valid. But int arr[]; without any initializer is invalid — the compiler does not know how much memory to allocate. This would cause a compilation error. The size must be known at compile time, either explicitly or from the initializer.

Q13 (Write/Workout — Hard)

Write a C++ program that copies the contents of one string to another WITHOUT using the strcpy() function.

#include <iostream>
using namespace std;

int main()
{
    char source[] = "Hello World";
    char dest[20];
    int i;

    for (i = 0; source[i] != '\0'; i++)
    {
        dest[i] = source[i];
    }
    dest[i] = '\0';  // Manually add null terminator!

    cout << "Source: " << source << endl;
    cout << "Destination: " << dest << endl;

    return 0;
}

Explanation: The loop copies each character from source to dest one by one, stopping when it encounters '\0' in the source. After the loop, i points to the position where '\0' was in the source. We MUST manually add dest[i] = '\0' to properly terminate the destination string. If you forget this, the destination string will not be properly terminated and printing it may produce garbage after the copied content. This exercise shows what strcpy() does internally.

Q14 (MCQ — Hard)

What is the output?

int a[3] = {1, 2, 3};
int b[3];
b = a;
cout << b[0];
A) 1
B) Garbage value
C) Compilation error
D) 0

Answer: C

You cannot assign one array to another using the = operator in C++. Arrays are not assignable. The statement b = a; is a compilation error. To copy arrays, you must either use a loop to copy element by element, or use memcpy() from <cstring>. This rule applies to all arrays, including character arrays (where you use strcpy() instead of =). This is a fundamental limitation of C-style arrays.

Q15 (MCQ — Hard)

What is the output?

int arr[4] = {5, 10, 15, 20};
int *p = arr;
cout << *(p + 2);
A) 5
B) 10
C) 15
D) Address of arr[2]

Answer: C

When an array name is used in an expression, it decays to a pointer to its first element. So p = arr makes p point to arr[0]. p + 2 points to arr[2] (pointer arithmetic: adds 2 × sizeof(int) = 8 bytes to the address). *(p + 2) dereferences that pointer, giving the VALUE at arr[2], which is 15. If it were p + 2 without the *, it would print the address. This tests understanding of the relationship between arrays and pointers.

Q16 (Write a Program — Hard)

Write a C++ program that reads a string and reverses it WITHOUT using the strrev() function.

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[50], temp;
    int len, i, j;

    cout << "Enter a string: ";
    cin >> str;

    len = strlen(str);

    for (i = 0, j = len - 1; i < j; i++, j--)
    {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }

    cout << "Reversed: " << str << endl;
    return 0;
}

Explanation: The logic is a swap algorithm. We use two indices: i starting from the beginning and j starting from the end. We swap str[i] and str[j], then move i forward and j backward. We continue while i < j (stop when they meet or cross). For "Hello": swap H↔o → "oellH", swap e↔l → "olleH", i=2, j=2, loop ends. The null terminator stays in place because we never move it — it is always at position len. This is the same algorithm used in palindrome checking, but with swapping instead of just comparing.

Q17 (MCQ — Hard)

How many total bytes does char names[3][15] = {"Abebe", "Kebede", "Challa"}; occupy?

A) 19
B) 22
C) 45
D) 3

Answer: C

Total bytes = rows × columns × sizeof(char) = 3 × 15 × 1 = 45 bytes. Even though “Abebe” (6 bytes including ‘\0’), “Kebede” (7 bytes), and “Challa” (7 bytes) together use only 20 bytes of actual data, the array still occupies the full 45 bytes because each row is allocated 15 characters regardless of how many are used. The remaining positions in each row are filled with ‘\0’. This is why choosing appropriate column sizes matters for memory efficiency.

Q18 (Short Answer — Hard)

Explain the difference between char s[] = "Hello"; and char *s = "Hello";. Can you modify the content in both cases?

Answer:

char s[] = "Hello"; creates an array on the stack with a copy of “Hello\0”. You CAN modify it: s[0] = 'h'; works fine.

char *s = "Hello"; creates a pointer to a string literal stored in read-only memory. Attempting to modify it (s[0] = 'h';) causes undefined behavior — it may crash or seem to work on some compilers. Modern compilers may even warn or error on this.

Key difference: The array version owns a modifiable copy. The pointer version points to read-only memory. For modifiable strings, always use the array version.

Q19 (Write/Workout — Hard)

Write a C++ program that merges two sorted arrays into a single sorted array.

#include <iostream>
using namespace std;

int main()
{
    int a[] = {1, 3, 5, 7, 9};
    int b[] = {2, 4, 6, 8, 10};
    int c[10];
    int n1 = 5, n2 = 5;
    int i = 0, j = 0, k = 0;

    while (i < n1 && j < n2)
    {
        if (a[i] < b[j])
            c[k++] = a[i++];
        else
            c[k++] = b[j++];
    }

    // Copy remaining elements from a
    while (i < n1)
        c[k++] = a[i++];

    // Copy remaining elements from b
    while (j < n2)
        c[k++] = b[j++];

    cout << "Merged sorted array:" << endl;
    for (int m = 0; m < 10; m++)
        cout << c[m] << " ";

    return 0;
}
// Output: 1 2 3 4 5 6 7 8 9 10

Explanation: This is the classic merge algorithm (part of merge sort). We use three indices: i for array a, j for array b, k for the merged array c. We compare a[i] and b[j], and copy the smaller one to c[k], then advance the corresponding index. When one array is exhausted, we copy all remaining elements from the other array. Since both input arrays are already sorted, the result is also sorted. Time complexity: O(n1 + n2).

Q20 (MCQ — Hard)

What is the output?

int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++)
    arr[i] = arr[5 - 1 - i];
for (int i = 0; i < 5; i++)
    cout << arr[i] << " ";
A) 50 40 30 20 10
B) 50 50 50 50 50
C) 10 10 10 10 10
D) 10 20 30 20 10

Answer: B

This is a tricky question! The code TRIES to reverse the array but fails because it overwrites elements as it goes. Let me trace: i=0: arr[0] = arr[4] = 50. Now arr = {50, 20, 30, 40, 50}. i=1: arr[1] = arr[3] = 40. Now arr = {50, 40, 30, 40, 50}. i=2: arr[2] = arr[2] = 30 (no change). i=3: arr[3] = arr[1] = 40 (arr[1] is now 40, not 20!). i=4: arr[4] = arr[0] = 50 (arr[0] is now 50, not 10!). Final: {50, 40, 30, 40, 50}.

Wait, that gives option D. But let me re-trace more carefully: After i=0: {50,20,30,40,50}. After i=1: arr[1]=arr[3]=40 → {50,40,30,40,50}. After i=2: arr[2]=arr[2]=30 → {50,40,30,40,50}. After i=3: arr[3]=arr[1]=40 → {50,40,30,40,50}. After i=4: arr[4]=arr[0]=50 → {50,40,30,40,50}. Output: 50 40 30 40 50. This is option D. The code fails to properly reverse because it overwrites elements before they are read — you need a temporary variable and swap from both ends simultaneously.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top