PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » CPP Exercises » C++ Array Exercises

C++ Array Exercises

Updated on: December 10, 2025 | Leave a Comment

Arrays are the foundational data structure in C++ and mastering them is essential for efficient coding and understanding complex structures like vectors and matrices.

This comprehensive guide provides 30+ hands-on C++ array exercises, ranging from beginner-level operations to intermediate and advanced algorithmic challenges.

Each exercise is presented with a clear problem statement, a helpful hint, a complete C++ solution, and a detailed explanation.

What You Will Practice:

The exercises cover the below key array topics:

  • Traversal & Basic Arithmetic: Reading, printing (1D/2D), Sum, Average, Max/Min value, and simple searching.
  • Manipulation: Reversing, Swapping, Inserting, Deleting, and Rotating arrays.
  • Sorting & Ordering: Ascending/Descending sort, finding the Second Max/Min, and removing duplicates.
  • Filtering & Counting: Identifying Negative elements, Duplicates, and Unique elements.
  • Matrices (2D Arrays): Input/Output, Total/Diagonal Sum, Transpose, and Addition.
  • Merging: Efficiently merging two sorted arrays
+ Table Of Contents

Table of contents

  • Exercise 1: Initialize and Print Array
  • Exercise 2: Sum of Elements
  • Exercise 3: Find Maximum
  • Exercise 4: Linear Search
  • Exercise 5: Count Occurrences
  • Exercise 6: Reverse Array
  • Exercise 7: Copy Array
  • Exercise 8: Print Even Numbers
  • Exercise 9: Swap First and Last
  • Exercise 10: Display Unique Elements
  • Exercise 11: Element Index Check
  • Exercise 12: Sort Array (Ascending)
  • Exercise 13: Sort Array (Descending)
  • Exercise 14: Insert Element
  • Exercise 15: Delete Element
  • Exercise 16: Second Largest
  • Exercise 17: Replace All Zeros
  • Exercise 18: Check if Array is Sorted
  • Exercise 19: Rotate Left
  • Exercise 20: Rotate Right
  • Exercise 21: Remove Duplicates
  • Exercise 22: Check Palindrome
  • Exercise 23: Matrix Input/Output
  • Exercise 24: Matrix Sum
  • Exercise 25: Diagonal Sum
  • Exercise 26: Transpose Matrix
  • Exercise 27: Matrix Addition
  • Exercise 28: Equilibrium Index
  • Exercise 29: Missing Number
  • Exercise 30: Majority Element
  • Exercise 31: Pair Sum
  • Exercise 32: Merge Two Sorted Arrays
  • Exercise 33: Rotate Array by K Positions

Exercise 1: Initialize and Print Array

Problem Statement: Create a C++ program that declares an integer array of size 5. Prompt the user to enter 5 integer values, store these values sequentially in the array, and then print all 5 elements to the console on a single line, separated by spaces.

Expected Output:

Enter 5 integers:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50

The elements in the array are: 10 20 30 40 50
+ Hint

You will need a for loop to iterate from index 0 up to, but not including, the size of the array (5) for reading the input. Use another for loop to print the elements.

+ Show Solution
#include <iostream>

int main() {
    // 1. Declare an array of size 5
    int arr[5];
    int size = 5;

    std::cout << "Enter 5 integers:\n";

    // 2. Read input into the array
    for (int i = 0; i < size; ++i) {
        std::cout << "Element " << i + 1 << ": ";
        std::cin >> arr[i];
    }

    std::cout << "\nThe elements in the array are: ";

    // 3. Print the elements
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise demonstrates array declaration and basic traversal using a for loop.

  • The first loop uses the index variable i to access and modify each element sequentially using std::cin >> arr[i];.
  • The second loop then iterates over the exact same indices to read and print the stored values to the console, confirming successful initialization.

Exercise 2: Sum of Elements

Problem Statement: Write a C++ program that calculates the sum of all integer elements stored in an array. Initialize an array of size 5 with some hardcoded values (e.g., 10, 20, 30, 40, 50) and print the total sum.

Given:

int arr[] = {10, 20, 30, 40, 50};Code language: C++ (cpp)

Expected Output:

The sum of all elements is: 150
+ Hint
  • Initialize a variable, let’s call it total_sum, to zero before starting the array traversal.
  • Inside the for loop, add the value of the current array element to this variable in each iteration.
+ Show Solution
#include <iostream>

int main() {
    // Array initialized with hardcoded values
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    int total_sum = 0; // Initialize sum to zero

    // Loop through the array
    for (int i = 0; i < size; ++i) {
        // Accumulate the sum
        total_sum += arr[i];
    }

    std::cout << "The sum of all elements is: " << total_sum << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • A variable total_sum is used to store the result.
  • The for loop iterate every element, and the line total_sum += arr[i]; iteratively adds the value of the current element to the running total.
  • The size calculation using sizeof is a common C++ technique to determine the length of a statically-sized array.

Exercise 3: Find Maximum

Problem Statement: C++ program to find the largest (maximum) element in a given integer array.

Given:

int arr[] = {15, 8, 27, 4, 19};Code language: C++ (cpp)

Expected Output:

The maximum element in the array is: 27
+ Hint
  • Start by assuming the very first element of the array is the maximum. Then, iterate through the rest of the array elements using a for loop.
  • In each iteration, if the current element is greater than your current maximum, update the maximum variable with the new, larger value.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {15, 8, 27, 4, 19};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Initialize max_element with the first element of the array
    int max_element = arr[0]; 

    // Iterate starting from the second element (index 1)
    for (int i = 1; i < size; ++i) {
        if (arr[i] > max_element) {
            max_element = arr[i]; // Update if a larger element is found
        }
    }

    std::cout << "The maximum element in the array is: " << max_element << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise uses an iterative approach to solve a search problem.

  • The variable max_element holds the largest value found so far. By initializing it to arr[0], we ensure a valid starting point.
  • The for loop compares every subsequent element to this running maximum. The process guarantees that by the time the loop finishes, max_element will hold the absolute largest value in the entire array.

Exercise 4: Linear Search

Problem Statement: Implement a C++ program that performs a linear search. Given an array, ask the user to enter a number to search for. If the number is found, print its index (position); otherwise, print a “Not Found” message.

Given:

int arr[] = {10, 50, 30, 70, 80, 20};Code language: C++ (cpp)

Expected Output:

Enter the number to search for: 30
Element 30 found at index: 2
+ Hint
  • Use an if condition inside the loop to see if the current element matches the target value.
  • As soon as a match is found, print the index and exit the loop immediately, as there’s no need to continue searching.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {10, 50, 30, 70, 80, 20};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target;
    int found_index = -1; // -1 indicates "not found"

    std::cout << "Enter the number to search for: ";
    std::cin >> target;

    // Perform Linear Search
    for (int i = 0; i < size; ++i) {
        if (arr[i] == target) {
            found_index = i; // Store the index
            break;           // Exit the loop immediately
        }
    }

    if (found_index != -1) {
        std::cout << "Element " << target << " found at index: " << found_index << std::endl;
    } else {
        std::cout << "Element " << target << " not found in the array." << std::endl;
    }

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise demonstrates the Linear Search algorithm.

  • It checks each element one by one from the start of the array. The variable found_index acts as a flag; it is initialized to -1 (an invalid index) and is only updated if a match is found.
  • The use of break optimizes the search by preventing unnecessary iterations once the element is located. After the loop, the value of found_index is checked to determine the final output.

Exercise 5: Count Occurrences

Problem Statement: Given an array, write a program to count and print how many times the number 3 appears in the array.

Given:

int numbers[] = {10, 20, 30, 40, 50};
int target = 3;Code language: C++ (cpp)

Expected Output:

The number 3 occurs 3 times.
+ Hint
  • Define a variable, let’s call it count, initialized to zero.
  • Iterate through the array using a for loop, and use an if statement to check if the current element is equal to the target number (3). If the condition is true, increment the count variable.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {1, 3, 2, 3, 4, 3, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target = 3;
    int count = 0; // Initialize counter

    // Iterate through the array elements
    for (int i = 0; i < size; ++i) {
        if (arr[i] == target) {
            count++; // Increment the counter when the target is found
        }
    }

    std::cout << "The number " << target << " occurs " << count << " times." << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This is another variation of the traversal pattern where an operation (incrementing a counter) is conditionally applied.

The count variable tallies the total number of times the target value (3) is found. Unlike the Linear Search, the for loop must continue until the end of the array to ensure every instance of the target is counted.

Exercise 6: Reverse Array

Problem Statement: Write a C++ program that reads an integer array, prints the original array, and then prints the elements in reverse order.

Given:

int arr[] = {10, 20, 30, 40, 50};Code language: C++ (cpp)

Expected Output:

Original array: 10 20 30 40 50 
Reversed array: 50 40 30 20 10
+ Hint

Change the direction of your for loop. Start the loop index at the last valid index (size - 1) and decrement the index until it reaches 0 (inclusive).

+ Show Solution
#include <iostream>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Original array: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    std::cout << "Reversed array: ";
    // Start at the last index (size - 1) and decrement to 0
    for (int i = size - 1; i >= 0; --i) { 
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise demonstrates reverse traversal.

  • Array indices run from 0 up to size - 1. To print in reverse, the for loop is initialized at i = size - 1 (the index of the last element).
  • The loop condition is set to continue as long as i is greater than or equal to 0, and the step is set to --i. This prints the elements from the end to the beginning.

Exercise 7: Copy Array

Problem Statement: Create two integer arrays, arr1 and arr2, both of size 5. Write a program to copy all elements from arr1 to arr2, and then print the elements of arr2 to verify the copy operation.

Given:

int arr1[] = {1, 2, 3, 4, 5};Code language: C++ (cpp)

Expected Output:

Elements of the copied array (arr2): 1 2 3 4 5
+ Hint
  • You must use a for loop to copy the elements individually. A simple assignment like arr2 = arr1; will not work for raw C-style arrays.
  • Use the loop index to access and assign the value from arr1[i] to arr2[i].
+ Show Solution
#include <iostream>

int main() {
    int arr1[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr1) / sizeof(arr1[0]);

    // Declare the destination array with the same size
    int arr2[5]; 

    // Loop to copy elements from arr1 to arr2
    for (int i = 0; i < size; ++i) {
        arr2[i] = arr1[i]; // The actual copy operation
    }

    // Print arr2 to verify the copy
    std::cout << "Elements of the copied array (arr2): ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr2[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • This exercise highlights that C-style arrays in C++ do not support simple value assignment via the assignment operator (=). A deep copy requires manual element-by-element assignment.
  • The for loop iterates through the corresponding indices, ensuring that the value at arr1[i] is independently copied into the memory location designated for arr2[i].

Exercise 8: Print Even Numbers

Problem Statement: Given an integer array, write a C++ program that only prints the elements that are even numbers.

Given:

int arr[] = {1, 6, 3, 8, 5, 10, 7};Code language: C++ (cpp)

Expected Output:

The even numbers in the array are: 6 8 10
+ Hint
  • Iterate through the array using a for loop. Use the modulus operator (%) inside an if statement to check for divisibility by 2.
  • If arr[i] % 2 is equal to 0, the number is even and should be printed.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {1, 6, 3, 8, 5, 10, 7};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "The even numbers in the array are: ";

    // Iterate through the array
    for (int i = 0; i < size; ++i) {
        // Check if the number is perfectly divisible by 2
        if (arr[i] % 2 == 0) {
            std::cout << arr[i] << " ";
        }
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise introduces the concept of conditional printing during array traversal.

  • The modulus operator (%) is used to find the remainder of a division. If the remainder of dividing an element by 2 is 0 (arr[i] % 2 == 0), the number is an even number, and the program executes the printing action.
  • Otherwise, the number is skipped, effectively filtering the output to only show even values.

Exercise 9: Swap First and Last

Problem Statement: Write a C++ program to swap the value of the first element (index 0) with the value of the last element (index size - 1) in an array. Print the array before and after the swap.

Given:

int arr[] = {10, 20, 30, 40, 50};Code language: C++ (cpp)

Expected Output:

Array BEFORE swap: 10 20 30 40 50 
Array AFTER swap: 50 20 30 40 10
+ Hint

You will need a temporary variable (e.g., temp) to hold the value of the first element before overwriting it. The steps are:

  1. store arr[0] in temp
  2. assign arr[size - 1] to arr[0]
  3. assign temp to arr[size - 1].
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Array BEFORE swap: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    // Perform the swap
    int temp = arr[0];         // Step 1: Store the first element
    arr[0] = arr[size - 1];    // Step 2: Overwrite the first element with the last
    arr[size - 1] = temp;      // Step 3: Overwrite the last element with the stored first element

    std::cout << "Array AFTER swap: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise teaches the standard variable swap technique, which is crucial for sorting algorithms and in-place array modifications.

Without the temporary variable (temp), the value of the first element would be lost when the second step is executed, as it would be immediately overwritten by the value of the last element. The temporary variable preserves the data during the three-step exchange.

Exercise 10: Display Unique Elements

Problem Statement: Write a C++ program to find and print all the unique elements in an array. A unique element is one that appears only once.

Given:

int arr[] = {1, 5, 5, 2, 1, 3, 2, 4};Code language: C++ (cpp)

Expected Output:

Unique elements are: 3 4
+ Hint
  • This requires nested loops. For every element at index i, check all other elements at index j to see if there is a duplicate.
  • If the inner loop completes without finding any match (where i != j), the element arr[i] is unique. Use a boolean flag or a counter in the inner loop.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {1, 5, 5, 2, 1, 3, 2, 4};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Unique elements are: ";

    // Outer loop iterates through each element to check uniqueness
    for (int i = 0; i < size; ++i) {
        bool is_unique = true;
        
        // Inner loop checks the current element (arr[i]) against all others
        for (int j = 0; j < size; ++j) {
            // Check for duplicates, but skip checking the element against itself (i != j)
            if (i != j && arr[i] == arr[j]) {
                is_unique = false;
                break; // Found a duplicate, no need to check further
            }
        }
        
        if (is_unique) {
            std::cout << arr[i] << " ";
        }
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise introduces the use of nested loops for comparison-based array problems.

  • The outer loop selects an element, and the inner loop checks the selected element against every other element in the array. The bool is_unique flag tracks the status.
  • If a duplicate is found (is_unique becomes false), the inner loop is immediately terminated using break. If the inner loop completes with is_unique still being true, the element is printed.

Exercise 11: Element Index Check

Problem Statement: Given an array, and an index k=2, write a program to check if the value at index k is greater than the value at index k-1 and less than the value at index k+1. Print True or False.

Given:

int arr[] = {2, 3, 1, 4};Code language: C++ (cpp)

Expected Output:

The condition is: True
+ Hint
  • Access the array elements directly using the index k.
  • Before accessing k-1 and k+1, you must first check if k is a valid middle index (i.e., k > 0 and k < size-1).
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {10, 25, 40, 55, 70};
    int size = sizeof(arr) / sizeof(arr[0]);
    int k = 2; // Index to check (value 40)

    bool result = false;

    // Check boundary conditions first
    if (k > 0 && k < size - 1) {
        // Check if arr[k] > arr[k-1] AND arr[k] < arr[k+1]
        if (arr[k] > arr[k - 1] && arr[k] < arr[k + 1]) {
            result = true;
        }
    }
    // For invalid k, result remains false

    std::cout << "The condition is: " << (result ? "True" : "False") << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • This exercise emphasizes boundary checking and direct index access.
  • The if condition ensures that the program does not attempt to access memory outside the array bounds (e.g., index -1 or index 5 in a size-5 array), which would cause a runtime error.
  • The core logic then uses the logical AND operator (&&) to verify both comparison conditions simultaneously.

Exercise 12: Sort Array (Ascending)

Problem Statement: Write a C++ program to sort the elements of an integer array in ascending order. Print the array after sorting. (For this exercise, you may use the standard library std::sort function).

Given:

int arr[] = {5, 2, 8, 1, 9, 4};Code language: C++ (cpp)

Expected Output:

Array before sorting: 5 2 8 1 9 4 
Array AFTER sorting (Ascending): 1 2 4 5 8 9
+ Hint
  • Include the <algorithm> header file.
  • Use the std::sort function, passing the start pointer (arr) and the end pointer (arr + size) of the array as arguments.
+ Show Solution
#include <iostream>
#include <algorithm> // Required for std::sort

int main() {
    int arr[] = {5, 2, 8, 1, 9, 4};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Array before sorting: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    // Use the standard library sort function for ascending order
    std::sort(arr, arr + size);

    std::cout << "Array AFTER sorting (Ascending): ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise focuses on using the powerful Standard Library function std::sort.

  • The function requires two iterators (pointers for raw arrays): one pointing to the beginning of the range (arr) and one pointing one past the end of the range (arr + size).
  • By default, std::sort uses a highly optimized algorithm (typically Introsort) to arrange the elements in non-decreasing (ascending) order.

Exercise 13: Sort Array (Descending)

Problem Statement: Write a C++ program to sort the elements of an integer array in descending order. Print the array after sorting.

Given:

int arr[] = {5, 2, 8, 1, 9, 4};Code language: C++ (cpp)

Expected Output:

Array AFTER sorting (Descending): 9 8 5 4 2 1
+ Hint

If using std::sort, you must provide a third argument: a comparison function or a functor (like std::greater<int>) that defines the descending order logic.

+ Show Solution
#include <iostream>
#include <algorithm>
#include <functional> // Required for std::greater

int main() {
    int arr[] = {5, 2, 8, 1, 9, 4};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Use the standard library sort function for descending order
    // std::greater<int>() is the comparator for reverse order
    std::sort(arr, arr + size, std::greater<int>());

    std::cout << "Array AFTER sorting (Descending): ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

Sorting in descending order requires defining a custom comparison rule.

By passing std::greater<int>() as the third argument to std::sort, we instruct the sorting algorithm to place elements where the left operand is greater than the right operand, resulting in a reverse-sorted (descending) sequence.

Exercise 14: Insert Element

Problem Statement: Given a sorted array, insert a new element (e.g., 25) at a specific position (e.g., index 2). This requires shifting existing elements to the right to create space. Print the resulting array. Assume the array has enough space.

Given:

int arr[10] = {10, 20, 30, 40, 50}; // Array with space
int current_size = 5;
int element_to_insert = 25;
int position = 2; // Insertion indexCode language: C++ (cpp)

Expected Output:

Array after insertion: 10 20 25 30 40 50
+ Hint
  • Start from the last element and move elements one position to the right down to the insertion position.
  • For an array of size N, the loop should go from i = N - 1 down to the insertion index.
  • Then, place the new element in the now-empty insertion spot. Remember to increment the logical size of the array.
+ Show Solution
#include <iostream>

int main() {
    int arr[10] = {10, 20, 30, 40, 50}; // Array with space
    int current_size = 5;
    int element_to_insert = 25;
    int position = 2; // Insertion index

    // 1. Shift elements to the right starting from the end
    for (int i = current_size; i > position; --i) {
        arr[i] = arr[i - 1];
    }

    // 2. Insert the new element
    arr[position] = element_to_insert;

    // 3. Update the size
    current_size++;

    std::cout << "Array after insertion: ";
    for (int i = 0; i < current_size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This is an exercise in array modification. Since raw arrays have fixed memory, insertion requires manual shifting.

The for loop iterates backward from the new end position down to the insertion position (position + 1). This ensures that existing data is copied before the index is overwritten, preventing data loss. After shifting, the element is placed in the position, and the array’s effective size is incremented.

Exercise 15: Delete Element

Problem Statement: Given an array, delete the element at a specific index (e.g., index 3, which is 40). This requires shifting the remaining elements to the left to close the gap. Print the resulting array.

Given:

int arr[] = {10, 20, 30, 40, 50};
int current_size = 5;
int delete_position = 3; // Index of element 40Code language: C++ (cpp)

Expected Output:

Array after deletion: 10 20 30 50
+ Hint
  • Start shifting elements from the index right after the deletion index (index + 1).
  • The loop should iterate from i = deletion_index up to size - 2, assigning arr[i + 1] to arr[i]. Remember to decrement the logical size of the array.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int current_size = 5;
    int delete_position = 3; // Index of element 40

    if (delete_position < 0 || delete_position >= current_size) {
        std::cout << "Invalid deletion position." << std::endl;
        return 1;
    }

    // Shift elements to the left (overwrite the element to be deleted)
    for (int i = delete_position; i < current_size - 1; ++i) {
        arr[i] = arr[i + 1];
    }

    // Decrement the size
    current_size--;

    std::cout << "Array after deletion: ";
    for (int i = 0; i < current_size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

Deletion in a raw array also requires manual shifting.

  • The for loop starts at the element to be deleted (i = delete_position) and copies the value of the next element (arr[i + 1]) into the current slot (arr[i]). This moves all subsequent elements one position left, effectively overwriting and removing the element at the deletion position.
  • The final step is to decrement the current_size to logically exclude the last (now duplicated) element.

Exercise 16: Second Largest

Problem Statement: Write a C++ program to find the second largest element in an unsorted array.

Given:

int arr[] = {12, 35, 1, 10, 34, 1};Code language: C++ (cpp)

Expected Output:

The second largest element is: 34
+ Hint
  • You can solve this efficiently in a single pass.
  • Initialize two variables: largest and second_largest, both to a very small number (or the first element).
  • Iterate through the array. If the current element is greater than largest, update second_largest = largest and then largest = current element.
  • Otherwise, if the current element is greater than second_largest but less than largest, only update second_largest.
+ Show Solution
#include <iostream>
#include <limits> // Required for std::numeric_limits

int main() {
    int arr[] = {12, 35, 1, 10, 34, 1};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Initialize largest and second_largest to the smallest possible integer value
    int largest = std::numeric_limits<int>::min();
    int second_largest = std::numeric_limits<int>::min();

    for (int i = 0; i < size; ++i) {
        if (arr[i] > largest) {
            // New largest found
            second_largest = largest; // Old largest becomes second largest
            largest = arr[i];
        } else if (arr[i] > second_largest && arr[i] < largest) {
            // Found a value smaller than largest but greater than second largest
            second_largest = arr[i];
        }
    }

    std::cout << "The second largest element is: " << second_largest << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This efficient method uses a single traversal, making it an O(N) solution.

  • It tracks the two largest numbers simultaneously. The first if block handles cases where a new absolute maximum is found.
  • The else if block handles cases where the current element is smaller than the current maximum but larger than the current second maximum, thereby updating only the second_largest variable.
  • Initializing the variables using std::numeric_limits<int>::min() ensures correct comparison even with negative numbers.

Exercise 17: Replace All Zeros

Problem Statement: Given an array, write a C++ program to replace all occurrences of the number 0 with the value -1. Print the modified array.

Given:

int numbers[] = {10, 20, 30, 40, 50};Code language: C++ (cpp)

Expected Output:

Original array: 1 0 5 0 8 0 2 
Modified array: 1 -1 5 -1 8 -1 2
+ Hint
  • Use a for loop to iterate through every element of the array.
  • Inside the loop, use an if condition to check if the current element is equal to 0. If it is, assign the new value, -1, to that array position.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {1, 0, 5, 0, 8, 0, 2};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Original array: ";
    for (int x : arr) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    // Loop to modify the array
    for (int i = 0; i < size; ++i) {
        if (arr[i] == 0) {
            arr[i] = -1; // Replace 0 with -1
        }
    }

    std::cout << "Modified array: ";
    for (int x : arr) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise demonstrates in-place modification of an array.

The for loop iterates through the entire array. if the element meets the criteria (arr[i] == 0), its value is changed directly within the array’s memory location (arr[i] = -1). This process alters the array permanently for subsequent operations.

Exercise 18: Check if Array is Sorted

Problem Statement: Write a C++ program to check if an array is sorted in non-decreasing (ascending) order.

Given:

int arr1[] = {10, 20, 30, 40};
int arr2[] = {10, 30, 20, 40};Code language: C++ (cpp)

Expected Output:

Array 1 is sorted: True
Array 2 is sorted: False
+ Hint
  • You only need to compare each element with the element immediately following it.
  • Use a single for loop that runs from index 0 up to size - 2.
  • If at any point arr[i] > arr[i + 1], the array is unsorted, and you can immediately return false using the break statement.
+ Show Solution
#include <iostream>

bool is_sorted(int arr[], int size) {
    // We only need to check up to the second-to-last element (size - 2)
    for (int i = 0; i < size - 1; ++i) {
        // If the current element is greater than the next element, it is NOT sorted ascendingly
        if (arr[i] > arr[i + 1]) {
            return false;
        }
    }
    // If the loop completes without returning false, the array is sorted
    return true;
}

int main() {
    int arr1[] = {10, 20, 30, 40};
    int size1 = sizeof(arr1) / sizeof(arr1[0]);

    std::cout << "Array 1 is sorted: " << (is_sorted(arr1, size1) ? "True" : "False") << std::endl;

    int arr2[] = {10, 30, 20, 40};
    int size2 = sizeof(arr2) / sizeof(arr2[0]);
    
    std::cout << "Array 2 is sorted: " << (is_sorted(arr2, size2) ? "True" : "False") << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise demonstrates an efficient sequential comparison check.

  • To confirm ascending order, every pair of adjacent elements must satisfy the condition arr[i] <= arr[i + 1].
  • The loop runs up to size - 1 comparisons. Crucially, if the condition arr[i] > arr[i + 1] is ever true, the function immediately concludes the array is not sorted and terminates early, optimizing performance.

Exercise 19: Rotate Left

Problem Statement: Write a C++ program to rotate an array’s elements by one position to the left. The first element moves to the end, and all other elements shift one position earlier.

Given:

int arr[] = {1, 2, 3, 4, 5};Code language: C++ (cpp)

Expected Output:

Array after left rotation: 2 3 4 5 1
+ Hint
  • Store the first element (arr[0]) in a temporary variable before the loop.
  • Shift the remaining elements from index 1 to size - 1 one position to the left (arr[i - 1] = arr[i]).
  • Finally, assign the temporary variable to the last element (arr[size - 1]).
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Store the first element to be placed at the end
    int first_element = arr[0];

    // Shift elements one position to the left
    for (int i = 0; i < size - 1; ++i) {
        arr[i] = arr[i + 1];
    }

    // Place the stored first element at the end
    arr[size - 1] = first_element;

    std::cout << "Array after left rotation: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise demonstrates cyclic array shifting. The first element is saved to prevent loss.

  • The for loop efficiently moves all elements one position to the left, effectively overwriting the old first element’s position.
  • The loop stops at size - 2 because the element at size - 1 (the last element) is copied into the slot at size - 2.
  • Finally, the saved first_element is placed at the now-empty last index.

Exercise 20: Rotate Right

Problem Statement: Write a C++ program to rotate an array’s elements by one position to the right. The last element moves to the beginning, and all other elements shift one position later.

Given:

int arr[] = {1, 2, 3, 4, 5};Code language: C++ (cpp)

Expected Output:

Array after right rotation: 5 1 2 3 4
+ Hint
  • Store the last element (arr[size - 1]) in a temporary variable. Shift the remaining elements from index size - 2 down to 0 one position to the right (arr[i + 1] = arr[i]).
  • The loop must iterate backward. Finally, assign the temporary variable to the first element (arr[0]).
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Store the last element to be placed at the beginning
    int last_element = arr[size - 1];

    // Shift elements one position to the right (loop backwards)
    for (int i = size - 1; i > 0; --i) {
        arr[i] = arr[i - 1];
    }

    // Place the stored last element at the beginning
    arr[0] = last_element;

    std::cout << "Array after right rotation: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

Right rotation involves shifting elements backward in the array indices. The backward for loop is essential here: starting from the last valid index and decrementing ensures that the element at arr[i] is copied to arr[i + 1] before arr[i] is itself overwritten in the previous iteration.

This prevents data loss during the shift, and the saved last_element correctly fills the arr[0] slot at the end.

Exercise 21: Remove Duplicates

Problem Statement: Write a C++ program to eliminate duplicate elements from a sorted array in place. Given {1, 2, 2, 3, 4, 4, 4, 5} the resulting array should logically become {1, 2, 3, 4, 5} and the new size (5) should be returned.

Given:

int arr[] = {1, 2, 2, 3, 4, 4, 4, 5};Code language: C++ (cpp)

Expected Output:

Array after removing duplicates (New Size: 5): 1 2 3 4 5
+ Hint
  • Since the array is sorted, duplicates are adjacent. Use two pointers or indices, say i (for the iterating pointer) and j (for the pointer to the unique element’s position).
  • Only copy arr[i] to arr[j] when arr[i] is different from arr[j - 1]. Increment j only when a unique element is copied.
+ Show Solution
#include <iostream>

int remove_duplicates(int arr[], int size) {
    if (size == 0) return 0;
    
    // j tracks the position of the next unique element
    int j = 1; 

    // i tracks the currently examined element
    for (int i = 1; i < size; ++i) {
        // If the current element is different from the previous unique element
        if (arr[i] != arr[j - 1]) {
            arr[j] = arr[i]; // Copy the unique element to the j position
            j++;             // Move the unique element pointer forward
        }
        // If arr[i] is a duplicate, we do nothing and let i continue
    }
    return j; // j is the new size
}

int main() {
    int arr[] = {1, 2, 2, 3, 4, 4, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    // The function modifies the array in-place and returns the new size
    int new_size = remove_duplicates(arr, size);

    std::cout << "Array after removing duplicates (New Size: " << new_size << "): ";
    for (int i = 0; i < new_size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This is an advanced exercise demonstrating in-place modification using two pointers.

  • Since the array is sorted, only adjacent elements need comparison. The pointer j tracks the boundary between the unique elements (at indices 0 to j-1) and the rest of the array.
  • When the element at arr[i] is unique compared to the element just before the j boundary (arr[j - 1]), it is copied into the j slot, and the unique boundary is advanced. Duplicates are effectively skipped, resulting in a compacted array.

Exercise 22: Check Palindrome

Problem Statement: Write a C++ program to check if an array is a palindrome. An array is a palindrome if it reads the same forwards and backwards.

Given:

int arr1[] = {1, 2, 3, 2, 1};
int arr2[] = {1, 2, 3, 4};Code language: C++ (cpp)

Expected Output:

Array 1 is a palindrome: True
Array 2 is a palindrome: False
+ Hint
  • Use two pointers starting from the opposite ends of the array: left at index 0 and right at index size - 1.
  • Use a while loop that continues as long as left is less than right. In each iteration, check if arr[left] equals arr[right]. If they don’t match, return false immediately. If the loop completes, return true.
+ Show Solution
#include <iostream>

bool is_palindrome(int arr[], int size) {
    int left = 0;
    int right = size - 1;

    while (left < right) {
        // If elements at opposite ends don't match, it's not a palindrome
        if (arr[left] != arr[right]) {
            return false;
        }
        // Move pointers inward
        left++;
        right--;
    }
    // If the loop completes without finding a mismatch, it is a palindrome
    return true;
}

int main() {
    int arr1[] = {1, 2, 3, 2, 1};
    int size1 = sizeof(arr1) / sizeof(arr1[0]);
    
    std::cout << "Array 1 is a palindrome: " << (is_palindrome(arr1, size1) ? "True" : "False") << std::endl;
    
    int arr2[] = {1, 2, 3, 4};
    int size2 = sizeof(arr2) / sizeof(arr2[0]);
    
    std::cout << "Array 2 is a palindrome: " << (is_palindrome(arr2, size2) ? "True" : "False") << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This problem utilizes the two-pointer technique for efficient bidirectional comparison.

  • The while loop condition left < right ensures that the comparison only occurs up to the middle of the array, avoiding redundant checks.
  • If any element pair from opposite ends fails the equality check, the function immediately returns false. If all pairs match, the loop finishes, and the function confirms the array is a palindrome by returning true.

Exercise 23: Matrix Input/Output

Problem Statement: Create a C++ program that declares a 2D integer array (a matrix) of size 3 X 3. Prompt the user to enter 9 integer values and store them in the matrix. Finally, print the matrix in a standard row-column format.

Expected Output:

Enter 9 integers for the 3x3 matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter element [2][0]: 7
Enter element [2][1]: 8
Enter element [2][2]: 9

The matrix is:
1 2 3
4 5 6
7 8 9
+ Hint
  • You will need nested for loops.
  • The outer loop iterates through the rows (i) from 0 to 2, and the inner loop iterates through the columns (j) from 0 to 2.
  • Use arr[i][j] to access each element. Print a newline character (\n or std::endl) after the inner loop finishes to start a new row.
+ Show Solution
#include <iostream>

int main() {
    const int ROWS = 3;
    const int COLS = 3;
    int matrix[ROWS][COLS];

    std::cout << "Enter 9 integers for the 3x3 matrix:\n";

    // Input loop
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            std::cout << "Enter element [" << i << "][" << j << "]: ";
            std::cin >> matrix[i][j];
        }
    }

    std::cout << "\nThe matrix is:\n";

    // Output loop
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            std::cout << matrix[i][j] << "\t"; // Use tab for alignment
        }
        std::cout << std::endl; // Newline after each row
    }

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This exercise introduces multi-dimensional arrays.

  • A 3X3 matrix is represented as int matrix[3][3]. Accessing and processing elements always requires two indices: the first for the row (i) and the second for the column (j).
  • Nested for loops are the standard method for traversing 2D arrays, with the outer loop controlling the row movement and the inner loop handling column movement across that row.

Exercise 24: Matrix Sum

Problem Statement: Write a C++ program to calculate the sum of all elements in a hardcoded 3X3 matrix. Print the total sum.

Given:

const int ROWS = 3;
    const int COLS = 3;
    int matrix[ROWS][COLS] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };Code language: C++ (cpp)

Expected Output:

The sum of all elements in the matrix is: 45
+ Hint
  • Initialize a total_sum variable to 0. Use nested for loops to traverse every element in the matrix.
  • Inside the innermost loop, add the current element matrix[i][j] to total_sum.
+ Show Solution
#include <iostream>

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

    // Calculate sum using nested loops
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            total_sum += matrix[i][j];
        }
    }

    std::cout << "The sum of all elements in the matrix is: " << total_sum << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • This is the 2D array equivalent of Exercise 2 (Sum of Elements). Here sum is calculated using nested loops.
  • The outer loop ensures every row is processed, and the inner loop ensures every column element within that row is added to the running total_sum.

Exercise 25: Diagonal Sum

Problem Statement: Write a C++ program to calculate the sum of elements along the main diagonal of a square 3X3 matrix. The main diagonal consists of elements where the row index equals the column index (i.e., matrix[i][i]).

Given:

const int SIZE = 3; // Matrix is 3x3
int matrix[SIZE][SIZE] = {
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 9}
};Code language: C++ (cpp)

Expected Output:

The sum of the main diagonal elements is: 15
+ Hint

Since you only need the main diagonal elements, a single for loop is sufficient, iterating from i=0 to i=size}-1. In each iteration, add matrix[i][i] to the sum.

+ Show Solution
#include <iostream>

int main() {
    const int SIZE = 3; // Matrix is 3x3
    int matrix[SIZE][SIZE] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int diagonal_sum = 0;

    // Calculate the sum of the main diagonal (where row index == col index)
    for (int i = 0; i < SIZE; ++i) {
        diagonal_sum += matrix[i][i];
    }

    std::cout << "The sum of the main diagonal elements is: " << diagonal_sum << std::endl; // 1 + 5 + 9 = 15

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • This exercise optimizes traversal for a specific pattern. For a square matrix, the main diagonal elements are defined by the condition i = j.
  • Because of this equality, we only need a single loop where the loop index i is used for both the row and column access, making the calculation very efficient.

Exercise 26: Transpose Matrix

Problem Statement: Write a C++ program to find and print the transpose of a 3X3 matrix. The transpose is created by swapping the row and column indices (i.e., transpose[i][j] = original[j][i]).

Given:

const int ROWS = 3;
const int COLS = 3;
int matrix[ROWS][COLS] = {
     {1, 2, 3},
     {4, 5, 6},
     {7, 8, 9}
};Code language: C++ (cpp)

Expected Output:

Original Matrix:
1 2 3
4 5 6
7 8 9

Transposed Matrix:
1 4 7
2 5 8
3 6 9
+ Hint
  • Declare a second 3X3 matrix, transpose.
  • Use nested for loops to iterate through the original matrix.
  • Inside the loops, assign matrix[j][i] to transpose[i][j].
+ Show Solution
#include <iostream>

int main() {
    const int ROWS = 3;
    const int COLS = 3;
    int matrix[ROWS][COLS] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int transpose[COLS][ROWS]; // Rows and cols are conceptually swapped

    // Calculate the transpose
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            transpose[j][i] = matrix[i][j]; // Swap of indices
        }
    }

    std::cout << "Original Matrix:\n";
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            std::cout << matrix[i][j] << "\t";
        }
        std::cout << std::endl;
    }

    std::cout << "\nTransposed Matrix:\n";
    for (int i = 0; i < COLS; ++i) { // Loop uses COLS for outer and ROWS for inner for display
        for (int j = 0; j < ROWS; ++j) {
            std::cout << transpose[i][j] << "\t";
        }
        std::cout << std::endl;
    }

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • The transpose operation swaps the roles of rows and columns. In the calculation loop, the key operation is transpose[j][i] = matrix[i][j]. This takes the element at row i, column j of the original matrix and places it at row j, column i of the new matrix.
  • The size declaration for transpose is int transpose[COLS][ROWS], though for a 3X3 matrix, the dimensions remain 3X3.

Exercise 27: Matrix Addition

Problem Statement: Write a C++ program to add two 3X3 matrices, A and B, and store the result in a third matrix, C. Print the resulting matrix C. Matrix addition requires adding corresponding elements: C[i][j] = A[i][j] + B[i][j].

Given:

const int ROWS = 3;
const int COLS = 3;
int A[ROWS][COLS] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int B[ROWS][COLS] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
int C[ROWS][COLS]; // Result matrixCode language: C++ (cpp)

Expected Output:

Result Matrix (C = A + B):
10 10 10
10 10 10
10 10 10
+ Hint
  • Declare three 3X3 matrices.
  • Use nested for loops to iterate over all nine positions.
  • Inside the inner loop, perform the addition and assign the result directly to the corresponding position in the result matrix C.
+ Show Solution
#include <iostream>

int main() {
    const int ROWS = 3;
    const int COLS = 3;
    int A[ROWS][COLS] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    int B[ROWS][COLS] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
    int C[ROWS][COLS]; // Result matrix

    // Perform matrix addition
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    std::cout << "Result Matrix (C = A + B):\n";
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            std::cout << C[i][j] << "\t";
        }
        std::cout << std::endl;
    }

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • Matrix addition is element-wise and requires that both matrices have the same dimensions.
  • This program uses nested loops to ensure that for every position (i, j), the elements from matrix A and matrix B are summed and stored in the exact same position in matrix C.
  • The result is a 3X3 matrix where every element is 10 (e.g., 1+9=10, 5+5=10).

Exercise 28: Equilibrium Index

Problem Statement: Find an equilibrium index in an array. An index i is an equilibrium index if the sum of elements at indices less than i is equal to the sum of elements at indices greater than i. The empty array sum is 0.

Given:

int arr[] = {-7, 1, 5, 2, -4, 3, 0};Code language: C++ (cpp)

Expected Output:

Equilibrium index found at: 3
Equilibrium index found at: 6
+ Hint
  • First, calculate the total sum of the entire array.
  • Then, iterate through the array, tracking a left_sum. In each step, check if left_sum equals total_sum - left_sum - arr[i]. If it does, i is an equilibrium index. Update left_sum after the check.
+ Show Solution
#include <iostream>
#include <numeric>

int main() {
    int arr[] = {-7, 1, 5, 2, -4, 3, 0};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Step 1: Calculate the total sum of the array
    int total_sum = 0;
    for (int x : arr) {
        total_sum += x;
    }
    
    int left_sum = 0;
    
    // Step 2: Iterate and check for equilibrium
    for (int i = 0; i < size; ++i) {
        // total_sum - left_sum - arr[i] is the right_sum
        int right_sum = total_sum - left_sum - arr[i]; 

        if (left_sum == right_sum) {
            std::cout << "Equilibrium index found at: " << i << std::endl;
        }
        
        // Update left_sum for the next iteration
        left_sum += arr[i];
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This approach efficiently solves the problem in O(N) time by avoiding nested loops.

By pre-calculating the total_sum, the right sum (right_sum) can be instantly derived using the formula: RightSum = TotalSum - LeftSum - CurrentElement.

The variable left_sum accumulates the sum of elements before the current index i, allowing the check to be performed at every position.

Exercise 29: Missing Number

Problem Statement: Given an array of N - 1 distinct integers in the range of 1 to N (e.g., N=5, range 1-5, array {1, 2, 4, 5}), find the one missing number.

Given:

int arr[] = {1, 2, 4, 5};Code language: C++ (cpp)

Expected Output:

The missing number in the range 1 to 5 is: 3
+ Hint
  • Calculate the expected sum of numbers from 1 to N using the formula for the sum of an arithmetic series: ExpectedSum = N * (N + 1) / 2.
  • Then, calculate the actual sum of the elements present in the array. The missing number is the difference: MissingNumber = ExpectedSum - ActualSum.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {1, 2, 4, 5};
    int n_minus_1 = sizeof(arr) / sizeof(arr[0]);
    int N = n_minus_1 + 1; // The full range goes up to N (5 in this case)

    // Step 1: Calculate the expected sum (Sum of 1 to N)
    // Formula: N * (N + 1) / 2
    long long expected_sum = (long long)N * (N + 1) / 2;

    // Step 2: Calculate the actual sum of the array elements
    long long actual_sum = 0;
    for (int x : arr) {
        actual_sum += x;
    }

    // Step 3: Find the missing number
    int missing_number = expected_sum - actual_sum;

    std::cout << "The missing number in the range 1 to " << N << " is: " << missing_number << std::endl; // Output: 3

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This is an elegant O(N) solution that avoids sorting or complex data structures. It relies on the mathematical properties of the set.

By calculating the theoretical sum of the complete set of numbers (1 to N) and subtracting the actual sum of the incomplete array, the result is exactly the number that was absent. Using long long for the sums is good practice to prevent overflow, especially when N is large.

Exercise 30: Majority Element

Problem Statement: Find the majority element in an array of size n. The majority element is the element that appears more than n/2 times.

Given:

int arr[] = {2, 2, 1, 1, 1, 2, 2};Code language: C++ (cpp)

Expected Output:

The majority element is: 2
+ Hint
  • Use Moore’s Voting Algorithm. Initialize candidate and count (to 0). Iterate through the array: if count is 0, set candidate to the current element.
  • If the current element equals candidate, increment count; otherwise, decrement count. The final candidate is the majority element (assuming one exists).
+ Show Solution
#include <iostream>

int find_majority(int arr[], int size) {
    int candidate = 0;
    int count = 0;

    // Phase 1: Find the candidate using Moore's Voting Algorithm
    for (int i = 0; i < size; ++i) {
        if (count == 0) {
            candidate = arr[i];
            count = 1;
        } else if (arr[i] == candidate) {
            count++;
        } else {
            count--;
        }
    }

    // Phase 2: Verification (optional if majority is guaranteed)
    // A second loop can be added here to count occurrences of 'candidate'
    // to rigorously prove it is the majority element.

    return candidate;
}

int main() {
    int arr[] = {2, 2, 1, 1, 1, 2, 2};
    int size = sizeof(arr) / sizeof(arr[0]);

    int majority = find_majority(arr, size);

    std::cout << "The majority element is: " << majority << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

Moore’s Voting Algorithm is an advanced and highly efficient O(N) solution. It’s based on the idea that if an element appears more than n/2 times, it will always be the last element standing after all pairs of different elements are “cancelled out” (by decrementing count).

The algorithm cleverly finds the potential majority element in a single pass without needing a map or complex sorting.

Exercise 31: Pair Sum

Problem Statement: Given an array {1, 5, 7, -1, 5} and a target sum K=6, find and print the count of all pairs of elements whose sum equals K. (The pairs are (1, 5) and (-1, 7) and a second (1, 5), so the count is 3).

Given:

int arr[] = {1, 5, 7, -1, 5};Code language: C++ (cpp)

Expected Output:

Found pair: (1, 5)
Found pair: (1, 5)
Found pair: (7, -1)

Total number of pairs with sum 6 is: 3
+ Hint
  • The simplest (but O(N^2)) approach is to use nested loops.
  • The outer loop iterates with index i, and the inner loop iterates with index j starting from i + 1. Inside the inner loop, check if arr[i] + arr[j] equals the target sum K. If it does, increment a counter.
+ Show Solution
#include <iostream>

int main() {
    int arr[] = {1, 5, 7, -1, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target_sum = 6;
    int pair_count = 0;

    // Nested loops for O(N^2) complexity
    for (int i = 0; i < size; ++i) {
        // Inner loop starts from i + 1 to avoid duplicate pairs 
        // and avoid checking an element with itself.
        for (int j = i + 1; j < size; ++j) { 
            if (arr[i] + arr[j] == target_sum) {
                pair_count++;
                std::cout << "Found pair: (" << arr[i] << ", " << arr[j] << ")" << std::endl;
            }
        }
    }

    std::cout << "\nTotal number of pairs with sum " << target_sum << " is: " << pair_count << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This solution uses the straightforward brute-force approach with nested loops, resulting in an O(N^2) time complexity.

  • The outer loop fixes the first element of the pair.
  • The inner loop then checks all subsequent elements (j = i + 1) to see if the required sum is met. The starting index of the inner loop, i + 1, is critical to ensure that each pair is counted only once and that no element is paired with itself.

Exercise 32: Merge Two Sorted Arrays

Problem Statement: Write a C++ program to merge two sorted integer arrays into a third array, C, such that C is also sorted. The merging should be done efficiently in a single pass without using a built-in sort function on the final array C.

Given:

int A[] = {1, 5, 8, 10};
int sizeA = 4;
int B[] = {2, 6, 9, 12, 15};
int sizeB = 5;Code language: C++ (cpp)

Expected Output:

Merged sorted array C: 1 2 5 6 8 9 10 12 15
+ Hint
  • Use three pointers: i for array A, j for array B, and k for array C.
  • Use a while loop that continues as long as both i and j are within their array bounds.
  • In each iteration, compare A[i] and B[j] and copy the smaller one to C[k], incrementing the corresponding source pointer and k.
  • After the main loop, copy any remaining elements from the unexhausted array.
+ Show Solution
#include <iostream>
#include <algorithm>

int main() {
    int A[] = {1, 5, 8, 10};
    int sizeA = 4;
    int B[] = {2, 6, 9, 12, 15};
    int sizeB = 5;
    const int sizeC = sizeA + sizeB;
    int C[sizeC];

    int i = 0, j = 0, k = 0;

    // Merge until one array is exhausted
    while (i < sizeA && j < sizeB) {
        if (A[i] < B[j]) {
            C[k++] = A[i++];
        } else {
            C[k++] = B[j++];
        }
    }

    // Copy remaining elements of A, if any
    while (i < sizeA) {
        C[k++] = A[i++];
    }

    // Copy remaining elements of B, if any
    while (j < sizeB) {
        C[k++] = B[j++];
    }

    std::cout << "Merged sorted array C: ";
    for (int x : C) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • This exercise requires the two-pointer (or three-pointer) merge technique, which is the core of Merge Sort.
  • By maintaining pointers for both sorted input arrays, the smallest remaining element from either A or B is determined and copied into C in O(N) time complexity.
  • The subsequent while loops handle the remaining elements after one of the arrays runs out.

Exercise 33: Rotate Array by K Positions

Problem Statement: Write a C++ program to rotate an array [1, 2, 3, 4, 5, 6, 7] to the right by K=3 positions. The result should be [5, 6, 7, 1, 2, 3, 4].

Given:

int arr[] = {1, 2, 3, 4, 5, 6, 7};
int size = 7;
int k = 3;Code language: C++ (cpp)

Expected Output:

Array after right rotation by 3: 5 6 7 1 2 3 4
+ Hint

The most efficient in-place solution uses the reversal algorithm.

  1. Reverse the first size - K elements
  2. Reverse the last K elements
  3. Reverse the entire array. Ensure K is adjusted to K % size to handle cases where K is larger than the array size.
+ Show Solution
#include <iostream>
#include <algorithm>
#include <vector>

void reverse_array(int arr[], int start, int end) {
    while (start < end) {
        std::swap(arr[start], arr[end]);
        start++;
        end--;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7};
    int size = 7;
    int k = 3; 
    
    // Normalize k (rotation amount)
    k = k % size;

    // Reversal Algorithm for Right Rotation:
    
    // 1. Reverse the first (size - k) elements (e.g., {1, 2, 3, 4} -> {4, 3, 2, 1})
    reverse_array(arr, 0, size - k - 1); 

    // 2. Reverse the last k elements (e.g., {5, 6, 7} -> {7, 6, 5})
    reverse_array(arr, size - k, size - 1); 

    // 3. Reverse the entire array (e.g., {4, 3, 2, 1, 7, 6, 5} -> {5, 6, 7, 1, 2, 3, 4})
    reverse_array(arr, 0, size - 1); 

    std::cout << "Array after right rotation by " << k << ": ";
    for (int x : arr) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The reversal algorithm is the optimal in-place solution for array rotation, achieving O(N) time complexity with O(1) extra space.

The key is to realize that rotating right by K is equivalent to swapping the first N - K elements with the last K elements, which is elegantly achieved by the three reversal steps. Normalizing K with the modulus operator (k % size) ensures the rotation works correctly even if K is larger than the array size.

Filed Under: CPP Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

CPP Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: CPP Exercises
TweetF  sharein  shareP  Pin

  CPP Exercises

  • All C++ Exercises
  • C++ Exercise for Beginners
  • C++ Loops Exercise
  • C++ Functions Exercise
  • C++ Arrays Exercise
  • C++ String Exercise
  • C++ Pointers Exercise
  • C++ OOP Exercise
  • C++ File Handling Exercise
  • C++ Structures and Enums Exercise
  • C++ Templates & Generic Programming Exercise

All Coding Exercises

C Exercises C++ Exercises Python Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement