C++ program to find largest number of an array


Consider below is the input array, where you want to find the largest number of an array.

arr[5] = {1, 1000, 100, 10000, 10}

You should get output as 10000 which is the largest number.

1. C++ program to find the largest number of an array

#include <iostream>
#include <array>
using namespace std;

int main() 
{
    int i, size;
    int arr[5] = {1, 1000, 100, 10000, 10}; // initialize array
    
    for (i = 1; i < 5; i++) { // iterate forloop  for the length of the array
        if (arr[0] < arr[i]) // compare first element of the array with every other element
            arr[0] = arr[i]; // assign the largest number to arr[0]
    }
    
    cout << "Largest number of the array: "<< arr[0];

    return 0;
}

Run here

In the above program,

  • we have initialized the array with input.
  • Using for loop we are traversing array from second element till the last element of the array
  • Then we are comparing every element present in the array with the first element and then assigning the larger value to arr[0] variable
  • Printing the arr[0] which gives the largest value

Results

Largest number of the array:  10000

2. C++ program to find the largest number of an array with user provided input

#include <iostream>
using namespace std;

int main() 
{
    int i, size;
    cout << "Enter the size of the array: ";
    cin >> size;
    
    int arr[size]; //declaring array
    
    cout << "\nEnter the elements of  the array: \n";
    for (i = 0; i < size; i++)
    {   
      cin >> arr[i];
    }

    for (i = 1; i < size; i++) { // iterate forloop  for the length of the array
        if (arr[0] < arr[i]) // compare first element of the array with every other element
            arr[0] = arr[i]; // assign the largest number to arr[0]
    }
    
    cout << "Largest number of the array: "<< arr[0];

    return 0;
}

Try yourself here by providing input in the stdin section

In the above program,

  • We are taking array size and array elements from user.
  • Using for loop we are traversing array from second element till the last element of the array
  • Then we are comparing every element present in the array with the first element and then assigning the larger value to arr[0] variable
  • Printing the arr[0] which gives the largest value

Results

Enter the size of the array: 5
Enter the elements of  the array: 1
100
10
10000
1000
Largest number of the array:  10000