Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find largest number of an array

C++ Code Example — Array Programs

ADVERTISEMENT

WAP to find largest number of an array

Objective

Write a C++ program to find the largest number in an array.

Algorithm / Approach

  1. Read 5 elements into an array a.
  2. Assume the first element is the largest: max = a[0].
  3. Iterate from index 1 to the end.
  4. If the current element is strictly greater than max (max < a[i]), update the maximum.
  5. Print the maximum value.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int i, a[5] ;
 cout<<"Enter 5 Elements : ";
 for(i =0; i< 5; i++) {
  cin>>a[i];
 }
 int max = a[0];
 for(i =1; i< 5; i++) {
  if(max < a[i]) {
   max = a[i];
  }
 }
 cout<<"Max = "<< max<< endl;
return 0;
}

Expected Output

Enter 5 Elements : 12 34 56 43 32
Max = 56

Explanation of the Program

  • This is a standard Linear Search for a maximum value.
  • We temporarily assume the first element is the "champion". As we walk through the rest of the array, we challenge each element against our champion. If an element wins, it becomes the new champion.

Complexity

Time Complexity O(n)
Space Complexity O(n)
ADVERTISEMENT