Array function

write the function int secondlargest(int x[], int cap)
the function returns the second largest value in array x.assume the capacity of array x is at least 2.also assume the elemnt in the array are distinct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 #include <iostream>
using namespace std;
int secondlargest(int x[],int cap){
int currentlargest=a[0];
int secondlargest=0;
for(int i=0; i<size; i++){
if(a[i]>secondlargest){
secondlargest=a[i];

if(a[i]>currentlargest){
secondlargest=currentlargest;
currentlargest=a[i];
}
return secondlargest;
  }
 }
int main(){
int a[5]={4,7,3,9,1};
int b[4]={5,3,8,1};
cout<<secondlargest(a,5)<<endl;
cout<<secondlargest(b,4)<<endl;
return 0;
}
You can sort the array and output the second highest number.

for example, take int array[5]. If you sort this array properly, then you can simply output

cout << array[3] << " is the second largest number. ";

remember that the index of an array starts at 0.

can you help me how to do it!!
exp.cpp: In function âint secondlargest(int*, int)â:
exp.cpp:4: error: âaâ was not declared in this scope
exp.cpp:6: error: âsizeâ was not declared in this scope
exp.cpp:17: error: a function-definition is not allowed here before â{â token
exp.cpp:25: error: expected â}â at end of input
im getting these errors.
Here is an example of sorting that I made for you. If you have any questions please ask.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>

using namespace std;

int main()
{
    int arr[10];

    cout<<"Enter 10 integer values and I'll sort them in ascending order\n" << endl;
    for(int i=0; i<10; i++)
    {
        cout<< "value " <<i+1<< ":";
        cin >> arr[i];

    }

    int i,j,temp;

    for(i=0; i<10; i++)
    {
        for(j=0; j<10; j++)
        {
            if(arr[i]<arr[j])
            {
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }

    for(int z=0; z < 10; z++)
    {
        cout << arr[z] << "  ";
    }

    cout << endl;

    cout << "The second highest Number in this array " << arr[8] << endl;

    return 0;




Enter 10 integer values and I'll sort them in ascending order

value 1:5
value 2:15
value 3:66
value 4:88
value 5:44
value 6:59
value 7:66
value 8:99
value 9:100
value 10:4

4  5  15  44  59  66  66  88  99  100

The second highest Number in this array 99

Process returned 0 (0x0)   execution time : 11.201 s
Press any key to continue.
Last edited on
Topic archived. No new replies allowed.