Array Operations Technique and Code in C++

In this lecture we learn Array Operations Technique and Code in C++ like finding the maximum number, the second maximum number, and performing searches in an array. These operations form the bedrock of many algorithms and data-structure tasks. We will illustrate each with clear code snippets, discuss their time- and space-complexities, and show image prompts to support visual learning.

Finding the Maximum Number in an Array

Concept & explanation

When you have an array of n elements (unsorted), you often need to determine the largest (maximum) value. The simplest method is to iterate once through the array, keeping track of the largest seen so far.

Algorithm outline:

  1. Initialize a variable maxVal to the first element (or to a suitably small value).
  2. Loop from the second element to the end: if the current element > maxVal, update maxVal.
  3. At the end the maxVal holds the largest value.

Time complexity: O(n) one pass through the array.
Space complexity: O(1) only one extra variable used.

Code snippet (C++)
#include <iostream>
using namespace std;

int main() {
    int arr[] = { 3, 57, 12, 98, 32 };
    int n    = sizeof(arr) / sizeof(arr[0]);
    int maxVal = arr[0];  // assume at least one element

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

    cout << "The largest element in the array is " << maxVal << endl;
    return 0;
}
Key points/tips
  • Make sure the array is non-empty; otherwise you may start with an invalid initial value.
  • If you allow negative numbers, initializing to a very small value (e.g., INT_MIN) is safer if you don’t take arr[0].
  • This method works for unsorted arrays; no sorting is needed.
Array Operations Technique and Code in C++

If you are a beginner in C++, you may face some difficulties in arrays declaration and initialization, here is a step by step easy guide on Declaration and initialization in array in C.

Finding the Second Maximum Number in an Array

Concept & explanation

Finding the largest value is straightforward, but often you also need the second largest (the “runner-up”) value. This is slightly trickier if you want to account for duplicates (e.g., the largest value appears more than once). The goal: find the largest distinct element and then the next largest distinct element.

Popular approaches:

  • Single-pass method: use two variables firstMax and secondMax; traverse once.
  • Sorting method: sort the array and then pick the largest and then the next distinct value.

Single-pass algorithm outline:

  1. Initialize firstMax = INT_MIN, secondMax = INT_MIN.
  2. For each element x in the array:
    • If x > firstMax, then secondMax = firstMax, firstMax = x.
    • Else if x < firstMax and x > secondMax, then secondMax = x.
  3. At end: firstMax is max, secondMax is second max (or some sentinel if none).

Time complexity: O(n)
Space complexity: O(1)

Code snippet (C++)
#include <iostream>
#include <climits>
using namespace std;

int main() {
    int arr[] = { 34, 5, 16, 14, 56, 7, 56 };
    int n     = sizeof(arr) / sizeof(arr[0]);

    int firstMax  = INT_MIN;
    int secondMax = INT_MIN;

    for (int i = 0; i < n; i++) {
        if (arr[i] > firstMax) {
            secondMax = firstMax;
            firstMax  = arr[i];
        }
        else if (arr[i] < firstMax && arr[i] > secondMax) {
            secondMax = arr[i];
        }
    }

    cout << "Maximum element is: " << firstMax << endl;
    if (secondMax == INT_MIN) {
        cout << "Second Maximum element does not exist" << endl;
    } else {
        cout << "Second Maximum element is: " << secondMax << endl;
    }

    return 0;
}
Edge-cases & tips
  • If all elements are equal, there is no distinct second maximum (handle appropriately).
  • If array length < 2, obviously second max cannot exist.
  • If you use the sorting approach: be mindful of duplicates (skip equal-to-max values).
  • Single-pass is more efficient (no sorting) and uses constant extra space.

Searching in an Array

Concept & explanation

Searching means determining whether a given target value exists or exceed in an array (and optionally returning its index). In unsorted arrays, the simplest method is linear (sequential) search: check each element one by one.

Algorithm outline (linear search):

  1. Given array arr[], size n, and a target value x.
  2. Loop i from 0 to n-1: if arr[i] == x, return the index i.
  3. If loop ends without match, return sentinel (e.g., -1) meaning “not found”.

Time complexity: O(n)
Space complexity: O(1)

Optionally, if the array is sorted, a binary search may be used (O(log n)). But in this lecture we focus on unsorted array, so linear search is appropriate.

Code snippet (C++)
#include <iostream>
using namespace std;

int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i; // index found
        }
    }
    return -1; // not found
}

int main() {
    int arr[] = { 34, 78, 12, 56, 89, 23 };
    int n     = sizeof(arr) / sizeof(arr[0]);
    int target;
    cout << "Enter the number to search: ";
    cin  >> target;

    int result = linearSearch(arr, n, target);
    if (result != -1) {
        cout << "Element " << target << " found at index " << result << endl;
    } else {
        cout << "Element " << target << " not found in the array." << endl;
    }
    return 0;
}
Key points/tips
  • For unsorted arrays, linear search is simple, though not optimal for very large data.
  • For sorted arrays, if you need many searches, consider sorting once and applying binary search.
  • Always check array bounds and ensure you handle “not found” correctly (e.g., return -1).
  • If multiple occurrences exist, you might want to return all indices or count of occurrences.

People also ask:

What are basic array operations in C++?

Common array operations include insertion, deletion, traversal, searching, and sorting. Each operation can be implemented using loops and conditional statements.

How can I find the largest element in an array in C++?

You can loop through the array, compare elements, and keep track of the maximum value using a variable, e.g.
int max = arr[0];
for(int i = 1; i < n; i++) if(arr[i] > max) max = arr[i];

How do you insert an element into an array in C++?

To insert, shift elements to the right from the insertion position and place the new value:
for(int i = n; i > pos; i–)
arr[i] = arr[i-1];
arr[pos] = value;
n++;

Leave a Reply

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