This program finds the largest element in an array. User is asked to enter the value of n(number of elements in array) then program asks the user to enter the elements of array. The program then finds the largest element and displays it.
To understand this program you should have the basic knowledge of loops, array and C++ if-else statement.
Example: A Program to find the largest element in an array of n elements
#include <iostream> using namespace std; int main(){ //n is the number of elements in the array int n, largest; int num[50]; cout<<"Enter number of elements you want to enter: "; cin>>n; /* Loop runs from o to n, in such a way that first * element entered by user is stored in num[0], second * in num[1] and so on. */ for(int i = 0; i < n; i++) { cout<<"Enter Element "<<(i+1)<< ": "; cin>>num[i]; } // Storing first array element in "largest" variable largest = num[0]; for(int i = 1;i < n; i++) { /* We are comparing largest variable with every element * of array. If there is an element which is greater than * largest variable value then we are copying that variable * to largest, this way we have the largest element copied * to the variable named "largest" at the end of the loop * */ if(largest < num[i]) largest = num[i]; } cout<<"Largest element in array is: "<<largest; return 0; }
Output:
Enter number of elements you want to enter: 5 Enter Element 1: 19 Enter Element 2: 21 Enter Element 3: 3 Enter Element 4: 89 Enter Element 5: 13 Largest element in array is: 89
Explanation:
User enters 5 which means the loop that stores the input values into the array runs 5 times, first entered value is stored in num[0], second in num[1] and so on.
The first element is assigned to the integer variable “largest”, this means that before starting of the second loop the value of largest is 19.
First Iteration of second loop: 19, which is the value of “largest” variable is compared with 21, since 21 is greater than 19, the “if” condition is true and the value of largest is now 21.
Second Iteration of loop: 21 (the value of largest) is compared with 3, since three is less than 21, nothing happens as the “if” condition is false.
Third Iteration of loop: 21 is compared with 89, 89 is greater than 21, “if” condition is true, the value of 89 is assigned to the “largest” variable.
Fourth Iteration of loop: 89(value of largest variable) is compared with 13, 13 is small so nothing happens.
Loop ended.
The value in “largest” variable is 89 at the end of loop, which we have displayed as the answer.
Leave a Reply