finding second smallest number using Dynamic Memory Allocation

Feb 29, 2016 at 6:58am
I have to code a program to find the smallest and the second smallest number form entered numbered by user.

Here is my code but it gets wrong answers for second smallest number in some cases.

for example:

if I enter :
10
2 3 5 6 7 4 5 8 0 39
it works correct (answer 0 2)
but if enter:
5
1 2 3 4 5

it gets wrong answer.

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
  #include <iostream>
using namespace std;

int main()
{
int *p;
int x;

cout << "Enter a number of student: ";
cin >> x;
p = new int[x];

for (int i = 0; i < x; i++)
{
cout << "Enter a grade: ";
cin >> *(p + i);
}
int min = 0;
int secmin = 0;
min = *p;
    for (int i=0; i<x; i++)
{
    if (*(p+i) < min)
    {
        secmin = min;
        min = *(p+i);
    }
    else if( *(p+i) < secmin)
        secmin = *(p+i);
/*  else 
    {
        secmin = *(p+i);    
    } */
}

cout << "Min num is : "<< min << "\nSecond Min num is: " << secmin <<  endl;

} 

Thanks in Advance
Feb 29, 2016 at 3:24pm
any ideas?
Feb 29, 2016 at 3:59pm
int secmin = 0;
Feb 29, 2016 at 5:56pm
@ne555
what should I do with that?
Feb 29, 2016 at 6:18pm
Explain it.
¿why did you set it to 0? ¿what if all the elements are greater than that?
Topic archived. No new replies allowed.