finding the second largest number in array

I'm trying to find the second largest number in my array of 10 and im getting really wierd errors of
class.cpp: In function âint secondLargest(int*, int)â:
class.cpp:11: error: name lookup of âiâ changed for new ISO âforâ scoping
class.cpp:7: error: using obsolete binding at âiâ

this is my code.

#include <iostream>
using namespace std;

int secondLargest(int a[], int size) {
int currentMax = a[0];
int secondMax=0;
for( int i = 0; i< size; i++) {
if (a[i] >secondMax)
secondMax = a[i]; }

if (a[i]>currentMax){
secondMax=currentMax;
currentMax=a[i];
}

return secondMax;
}
int main () {


int a[10]={1,2,3,4,5,6,7,8,9,10};
cout << "The max of the array is :" << secondLargest(a,10) << endl;

return 0;
}
1
2
3
4
5
6
7
8
9
for( int i = 0; i< size; i++) {
    if (a[i] >secondMax)
        secondMax = a[i]; }  // Closes for loop

    if (a[i]>currentMax){
        secondMax=currentMax;
        currentMax=a[i];
    }


You close your for loop on accident after the first if statement. Change it to this and it works
1
2
3
4
5
6
7
8
9
for( int i = 0; i< size; i++) {
    if (a[i] > secondMax)
        secondMax = a[i];

    if (a[i] > currentMax){
        secondMax=currentMax;
        currentMax=a[i];
    }
}
Last edited on
variable i is only available in the for Scope and you closed the bracket of for body
PS : Please used code tag
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int secondLargest(int a[], int size) {
int currentMax = a[0];
int secondMax=0;
for( int i = 0; i< size; i++) {
if (a[i] >secondMax)
secondMax = a[i]; 

if (a[i]>currentMax){
secondMax=currentMax;
currentMax=a[i];
}

return secondMax;
}
}
int main () {


int a[10]={1,2,3,4,5,6,7,8,9,10};
cout << "The max of the array is :" << secondLargest(a,10) << endl;

return 0;
}
Last edited on
thank you guys the second code worked but, it is giving me the answer as 1 when it is suppose to be 9
Topic archived. No new replies allowed.