C++ Program to Find the Largest and Smallest Elements in an Array

1. Introduction

Arrays are a foundational concept in programming and are used to store collections of data. One of the common operations performed on arrays is finding the largest and smallest elements. In this article, we'll develop a C++ program to determine these elements from a given array.

2. Program Overview

1. Define and initialize the array with numbers.

2. Traverse through the array while comparing elements to find the smallest and largest numbers.

3. Print out the smallest and largest numbers from the array.

3. Code Program

#include <iostream>
using namespace std;

int main() {
    int n;

    // Taking input for number of elements
    cout << "Enter the number of elements in the array: ";
    cin >> n;

    double arr[n];

    // Taking array input from the user
    cout << "Enter the elements of the array:" << endl;
    for(int i=0; i<n; i++) {
        cin >> arr[i];

    double max = arr[0];  // Assume first value to be the largest
    double min = arr[0];  // Assume first value to be the smallest

    // Traversing the array to find the largest and smallest elements
    for(int i=1; i<n; i++) {
        if(arr[i] > max) {
            max = arr[i];   // Update the maximum
        if(arr[i] < min) {
            min = arr[i];   // Update the minimum

    // Displaying the results
    cout << "Largest element in the array is: " << max << endl;
    cout << "Smallest element in the array is: " << min << endl;

    return 0;


For an array: 12, 34, 56, 78, 90, 11
Largest element is: 90
Smallest element is: 11

4. Step By Step Explanation

1. Array Initialization: After taking the size of the array from the user, each element is read into the array.

2. Max and Min Initialization: Initially, the first element of the array is assumed to be both the smallest and largest.

3. Array Traversal: As we traverse through the array, we compare each element to our current largest and smallest. If an element is larger than our current largest, we update our largest. Similarly, if an element is smaller than our current smallest, we update our smallest.

4. Display: After traversing the entire array, the determined largest and smallest elements are printed out.

This exercise gives you a basic understanding of how to traverse an array and perform simple comparisons to extract meaningful information.