Write a program to find the second largest number in an array of integers
Algorithm:-
1. Declare an array of integers and initialize it with some values.
2. Initialize largest = array[0] and secondLargest = array[0]
3. for i = 1 to size of array - 1 do
4. if array[i] > largest then
5. set secondLargest = largest
6. set largest = array[i]
7. else if array[i] > secondLargest and array[i] != largest then
8. set secondLargest = array[i]
9. end if
10. end for
11. Print the value of secondLargest.
Code(C++):-
#include <iostream>
using namespace std;
int main() {
int arr[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int size = sizeof(arr)/sizeof(arr[0]);
int largest = arr[0], secondLargest = arr[0];
for(int i = 1; i < size; i++) {
if(arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
}
else if(arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}
cout << "Second largest number in the array is: " << secondLargest << endl;
return 0;
}
Output:-
Second largest number in the array is: 90
Questions About Accenture:-
Recommended Post :-
Similar Questions:-
HCL Coding Questions:-Capgemini Coding Questions:-iMocha coding Questions:-Tech Mahindra coding questions:-Unthinkable Solutions coding questions:-- Swap the adjacent characters of the string
- Double the vowel characters in the string
- Character with their frequency
- Program to find the closest value
Must check this:-
Companies interview:-- Swap adjacent characters
- Double the vowel characters
- Check valid parenthesis
- Print the characters with their frequencies
- Find closest value
- Word Count
- Program of CaesarCipher
- Program to find the perfect city
- Annual Day | Tech Mahindra coding question
- Find the number of pairs in the array whose sum is equal to a given target.
Similar Questions:-
HCL Coding Questions:-
Capgemini Coding Questions:-
iMocha coding Questions:-
Tech Mahindra coding questions:-
Unthinkable Solutions coding questions:-
- Swap the adjacent characters of the string
- Double the vowel characters in the string
- Character with their frequency
- Program to find the closest value
Must check this:-
Companies interview:-
- Swap adjacent characters
- Double the vowel characters
- Check valid parenthesis
- Print the characters with their frequencies
- Find closest value
- Word Count
- Program of CaesarCipher
- Program to find the perfect city
- Annual Day | Tech Mahindra coding question
- Find the number of pairs in the array whose sum is equal to a given target.
0 Comments