Exercise:
Write a C++ program that can find the largest element of an array.
Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
int num;
float arr[100];
cout << "Insert the total number of entries (1 to 100): ";
cin >> num;
cout << endl;
for(int x = 0; x < num; ++x)
{
cout << x + 1 << ". ";
cin >> arr[x];
}
for(int x = 1;x < num; ++x)
{
if(arr[0] < arr[x]) // for smallest element arr[0] > arr[x]
arr[0] = arr[x];
}
cout << "\nThe largest number is: " << arr[0];
return 0;
}
Click Here to View the Output:
Insert the total number of entries (1 to 100): 4 243.4 567 34.567 563.45 The largest number is: 567
Click Here to View the Explanation:
- User is requested to enter the total number of entries
num
. The entries are taken from the user and stored in an arrayarr [x]
.x
is the number of elements the array contains. The value of x is requested from the user. - To check for the biggest element, a code is generated so that the first element and the second element of the array are compared.
- The bigger element is stored in
arr [0]
. - The first element is then compared to the third element. Then the fourth. The process continues until all the elements from first to last have been compared to each other.
- The bigger element throughout the check is stored in
arr [0]
. - The result is printed on the screen.