Question #13654

Write a function that accepts an array of non-negative integers and returns the second largest integer in the array. Return -1 if there is no second largest.

Expert's answer

#include<iostream>

// a is the array

// n is its length

int

max2(int * a, int n)

{

int m1=a[0]; // the maximal element

// find

maximal element of the array

for (int i=1; i<n; i++)

{

if

(m1<a[i]) m1=a[i];

};

int m2=-1; // the second maximal

element

for (int i=0; i<n; i++)

{

if (m1==a[i]) continue; // skip

maximal element

if ( m2 < a[i] ) m2=a[i];

};

return

m2;

};

// test

int main()

{

int a[] =

{31,4,6,0,17,8};

std::cout << max2(a, 6) << std::endl;

return 0;

};

// a is the array

// n is its length

int

max2(int * a, int n)

{

int m1=a[0]; // the maximal element

// find

maximal element of the array

for (int i=1; i<n; i++)

{

if

(m1<a[i]) m1=a[i];

};

int m2=-1; // the second maximal

element

for (int i=0; i<n; i++)

{

if (m1==a[i]) continue; // skip

maximal element

if ( m2 < a[i] ) m2=a[i];

};

return

m2;

};

// test

int main()

{

int a[] =

{31,4,6,0,17,8};

std::cout << max2(a, 6) << std::endl;

return 0;

};

## Comments

Assignment Expert30.08.12, 14:30You're welcome. We are glad to be helpful.

If you really liked our service please press like-button beside answer field. Thank you!

leyk28.08.12, 23:03Thank you for the response....

## Leave a comment