WAP to find largest number of an array
Objective
Write a C++ program to find the largest number in an array.
Algorithm / Approach
- Read 5 elements into an array
a. - Assume the first element is the largest:
max = a[0]. - Iterate from index 1 to the end.
- If the current element is strictly greater than
max(max < a[i]), update the maximum. - 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)