i want to find the second smallest number ib array but it is displaying second highest number
int max=0,second=0;
if(a[0]>a[1])
{
max=a[0];
second=a[1];
}
else
{
max=a[1];
second=a[0];
}
for( i=2;i<n;i++)
{
if(a>=max)
{
second=max;
max=a;
}
else

if(a>second)
second=a;

}
System.out.println("the second smallest nubmer is"+second);

I would suggest to sort the array first and then it is simple just reguest number on second possition. Also keep in mind that you may have first two number of same value so the second smallest should be on 3rd position(but that is just extra feature of your program)

Your instructor could also be extra devious and give you an array where all the indecies hold the same value. In which case the second smallest number would still be that value

no i gave all diff values

try this code.i have change few thing in u r code


int min=0,second=0;
if(a[0]<a[1])
{
min=a[0];
second=a[1];
}
else
{
min=a[1];
second=a[0];
}
for(int i=2;i<9;i++)
{
if(a<=min)
{
second=min;
min=a;
}
else
{
if(a<second)
second=a;
}
}
System.out.println("the second smallest nubmer is "+second);

i want to find the second smallest number ib array but it is displaying second highest number
int max=0,second=0;
if(a[0]>a[1])
{
max=a[0];
second=a[1];
}
else
{
max=a[1];
second=a[0];
}
for( i=2;i<n;i++)
{
if(a>=max)
{
second=max;
max=a;
}
else

if(a>second)
second=a;

}
System.out.println("the second smallest nubmer is"+second);

Already I can see problem here, in both cases if/else statement will be useless if first two numbers will be some of largest. You are expecting smallest number to be on one of first two positions in array.
Consider following array and think about it again arr = {4, 5, 1, 3, 2}

Already I can see problem here, in both cases if/else statement will be useless if first two numbers will be some of largest. You are expecting smallest number to be on one of first two positions in array.
Consider following array and think about it again arr = {4, 5, 1, 3, 2}

yaa sir u r right on run this code ans is 3 which is wrong.now i will try to slove this wiht my code.
thanking u

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.