That is the issue i am facing... I tried another logic by storing the digits in the array and printing the second largest integer by printing out the value of the second last element of the array :
Input : 9625
Output : 5
But the problem now is :
Input : 2299
Output: should be 2 but is 9 (obviously because sorted array will have 9 as the second last element).
How do i remove digits from array which are the same ? (As in i have to remove one 2 and one 9 in the above case)
look at std::set and stuff like that.
you can make it so your collection adds only unique numbers.
I'm not on my machine at the moment so i can't give you an example, but have a google of the emplace method. (once you've determined a character is actually a number). http://www.cplusplus.com/reference/set/set/emplace/
As this is a beginner's exercise I would have thought resorting to the standard algorithms and containers would be cheating? Also, I don't see a need for storing more values than largest and secondlargest.
Consider what should happen when n == largest !!
Andy
PS You could go back an finish fixing your "refined" code!
EDIT
Actually, if I fix your code (l -> largest) it does give 2 for the second largest digit in 2299, not 9 ??
#include <iostream>
usingnamespace std;
void test(int value);
int main ()
{
test(1234);
test(8735);
test(3377);
test(2299);
return 0;
}
void test(int value)
{
int c[16] = {0};
cout << "value = " << value << "\n";
cout << "\n";
int count = 0;
while(0 < value) {
c[count++] = value % 10;
value /= 10;
}
int largest = 0;
int secondlargest = 0;
for(int n : c)
{
if(largest<n)
{
secondlargest = largest;
largest = n;
}
elseif(n < largest && n > secondlargest )
{
secondlargest = n;
}
}
cout << "largest = " << largest << "\n";
cout << "second largest = " << secondlargest << "\n";
cout << "\n";
}
C++ Shell output:
value = 1234
largest = 4
second largest = 3
value = 8735
largest = 8
second largest = 7
value = 3377
largest = 7
second largest = 3
value = 2299
largest = 9
second largest = 2
As this is a beginner's exercise I would have thought resorting to the standard algorithms and containers would be cheating? Also, I don't see a need for storing more values than largest and secondlargest.
Such things can serve as inspiration. As to the second, the OP mentioned he was already dealing with a sorted array; std::unique (or equivalent code by the OP) seemed only natural.