Open In App

How to Find Largest Number in an Array in C++?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, arrays are used to store the collection of similar elements to be stored in adjacent memory locations. They can store data of any type such as int, char, float, etc. In this article, we will learn how to find the largest number in an array in C++.

For Example,

Input:
myVector = {1, 3, 10, 7, 8, 5, 4}

Output:
Largest Number = 10

Find the Largest Number in an Array in C++

To find the largest number in an array, we can use the std::max_element() function that takes the range in which it has to search for the max element as the arguments.

The syntax of max_element() is:

max_element(begin, end);

Here, the begin is the pointer or iterator to the start of the range and the end is the pointer or iterator to the end of the range.

This function will return the pointer or iterator to the maximum element in the range.

C++ Program to Find the Largest Number in an Array in C++

C++




// C++ program to find the largest number in an array
// without using std::max_element
#include <algorithm>
#include <iostream>
  
using namespace std;
  
int main()
{
    // Initialize the array
    int arr[] = { 1, 45, 54, 71, 76, 12 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Find the largest element in the array
    int max_num = *max_element(arr, arr + n);
  
    // Output the result
    cout << "Largest number in the array is: " << max_num
         << endl;
  
    return 0;
}


Output

Largest number in the array is: 76

Time complexity: O(n), where n is the number of elements in the array.
Space complexity: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads