C++ Program to find the largest and smallest number in an array using the function


In this program, You will learn how to find the largest and smallest number in an array using the function in C++.


List is :2 3 4 5 10 33 44 55 66 77

Largest & Smallest is: 77 2

Example: How to find the largest and smallest number in an array using a function in C++.

#include<iostream>
using namespace std;

void findNumber(int array[], int size) {

    int lg = array[0];
    int sm = array[0];

    for (int i = 0; i < size; i++) {
        if (lg < array[i]) {
            lg = array[i];
        }

        if (sm > array[i]) {
            sm = array[i];
        }
    }
    cout << "Largest number is:" << lg;
    cout << "\nSmallest number is:" << sm;
}

int main() {

    int array[10], i, size;

    cout << "Enter size of an array:";
    cin>>size;

    cout << "Enter array elements:";
    for (i = 0; i < size; i++) {
        cin >> array[i];
    }

    findNumber(array, size);

    return 0;
}

Output:

Enter size of an array:5
Enter array elements:40 50 10 20 30
Largest number is:50
Smallest number is:10