Adsense 728 * 15

Search

Custom Search

C, C++ program to find Largest Number/Element in Array



Write a C, C++ program to find largest element in an unsorted array. You can solve this problem using multiple approach.

First Approach

Sort an array. Once array is sorted,  last element of an array is largest.  For sorting you can use selection sort,  Bubble Sort , QuickSort, MergeSort etc.  Quicksort and MergeSort is best for sorting large elements in minimum time complexity( O(nlogn) ).

Second Approach

i) Take one flag and initialize it to first element of an array. 

ii) Run a loop and compare with each element, if any element is greater than the assigned value then update the largest variable.


Program to Find Smallest Element in An Array

More Question on Arrays

C++ Program to find largest element in an Array

#include <iostream>

using namespace std;

int main()
{
    
    /* Declare an array of length 50 .*/
    
 int arr[50],i,n,largest;


 cout<<"Enter how many elements you want to enter (keep less than 50)";
 cin>>n;

 for(i=0;i<n;i++){
  cin>>arr[i];
    }

   /* Initialize it to the first element of an array. */
   
   largest=arr[0];

    /* Traverse and compare each element of an array. */
    
 for( i=0;i<n;i++)
 {
  if(arr[i]>largest){
   
         largest=arr[i];
     }
 }


    cout<<" \nLargest element of an array is "<<largest;

    return 0;
}

    

Output :


Enter how many elements you want to enter (keep lesst than 50) : 5

7 3 8 2 4

Largest element of an array is 8

No comments:

Post a Comment