(Index of second largest element) Write a function that returns the index of the second largest element in an array of integers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

(Index of second largest element) Write a function that returns the index of the second largest element in an array of integers

Use the following header: int index_Of_Second_Largest_Element(int[] array) A sample run: 4 3 6 7 9 8 10 The index of the second largest element is 4 There is something wrong with my code here 😓 #include <iostream> using namespace std; int index_Of_Second_Largest_Element(int array[] ); int n, num[10], largest, second, array; int main(){ cout<<"Enter number of elements: "; cin>>n; for(int array=0; array<n; array++){ cout<<"Enter Array Element"<<(array+1)<<": "; cin>>num[array]; } cout<<"The index of the second Largest Element is: "<<index_Of_Second_Largest_Element(array[]); } int index_Of_Second_Largest_Element(int[] array){ if(num[0]<num[1]){ largest = num[1]; second = num[0];} else{ largest = num[0]; second = num[1];} for (int Array = 2; array< n ; array ++) { if (num[array] > largest) { second = largest; largest = num[array]; } else if (num[array] > second && num[array] != largest){second = num[array];} return second;}}

18th Dec 2020, 2:24 PM
Decoder 👩‍💻
5 Answers
+ 1
Is it your own code?
18th Dec 2020, 2:45 PM
Jayakrishna 🇮🇳
+ 1
It's not work for finding second largest element index. It's find 2nd largest element. And also it has some mistakes, I just corrected in other question just now.. You are passing array[] but declared num[] as array in main. And in function array argument not matching with prototype.. Same declaring array[] as array but using num as array..., In loop, declaring Array=2 but using array as variable.. All will cause name conflicts...
18th Dec 2020, 3:14 PM
Jayakrishna 🇮🇳
+ 1
//corrected in other thread, look once to understand it #include <iostream> using namespace std; int index_Of_Second_Largest_Element(int num[]); int n, num[10], largest, second, array; int main(){ cout<<"Enter number of elements: "; cin>>n; for(int array=0; array<n; array++){ cout<<"Enter Array Element"<<(array+1)<<": "; cin>>num[array]; } cout<<"The second Largest Element is: "<<index_Of_Second_Largest_Element(num); //1 edited } int index_Of_Second_Largest_Element(int num[]){ //2 edit if(num[0]<num[1]){ largest = num[1]; second = num[0]; } else{ largest = num[0]; second = num[1]; } for (int array = 2; array< n ; array ++) { //Edit 3 if (num[array] > largest) { second = largest; largest = num[array]; } else if (num[array] > second && num[array] != largest){ second = num[array]; } } //Edit 4 return second; } //hope you find out mistakes.. Or reply.. //you're welcome..Itsmenora
18th Dec 2020, 3:25 PM
Jayakrishna 🇮🇳
0
Yes and my friend
18th Dec 2020, 3:05 PM
Decoder 👩‍💻
0
Okkkay thank uu
18th Dec 2020, 3:16 PM
Decoder 👩‍💻