Adsense 728 * 15

Search

Custom Search

Program to Find Largest Number in an Array

Write a program to find largest number in an array. Given an unsorted array, find largest number in an array.
This type of questions are generally asked in interviews, where interviewer gives you an unsorted array and you have to find the largest and second largest element of an array.

Algorithm to Find Largest Number in an Array


First Method:

1. Sort an array.  For sorting you can use sorting algorithm such as Bubble Sort,  Selection Sort,  Insertion Sort, Quick Sort,  Merge Sort etc.

But i highly recommend use Quick Sort and Merge Sort for sorting as their time complexity is O(nlogn).

Sorting algorithms and their time complexity

2. Once the array is sorted pick the last element.

C Program to Find Largest Number in an Array


#include<stdio.h>

int main(){

  int i,j;

  
  /* Declare an array a. */

  int a[] = {3,6,2,1,8};
 
  /* Size of an array is 5 */

  int size = 5;
 
  // Sort the array using bubble sort

   for(i = 0; i < size; i++){   
    
     int temp=0;
    
     for(j=i+1;j<size;j++){
   
       if(a[i] > a[j]){
   
          temp = a[i];
          a[i] = a[j];
          a[j] = temp;

        }   
     }
  }

  /* Now the array is sorted you can pick the last element which is largest. */

   printf("Largest element is %d" ,a[size-1]);

}


Second Method:

1. Take an index and assign the first value of an array.




2.  Use loop and compare next value of an array to the value assigned in an index. If the value is greater then assigned this value to the index. Repeat this step until complete array is traversed.


#include<stdio.h>

int main(){

  int i,j;

  
  int a[] = {3,6,2,1,8};

  int size = sizeof(a)/sizeof(a[0]);
 
  /* Declare the largest variable and assign first value*/
  int largest = a[0]; 
 

   for(i=1;i<size;i++){   
   
     /* if a[i] is greater then assign to this value in largest index*/

     if(a[i]>largest) {
   
         largest = a[i];
       }   
   }

   printf("Largest element is %d" ,largest);

 }


No comments:

Post a Comment