Hi guys,

Quick question, I was trying out to determine the second smallest number of 10 random entered numbers, this is what I got:

#include <stdafx.h>
#include <iostream>
#include <iomanip>
using namespace std;

int main(void)
{
int s=0,x=0,y=0;

cout<< "Input ten random numbers with cin and determine the second smallest number"<< endl;

for(int i=0;i<10;i++)
{	

	cin>> x;cin.get();
	if (x<s)
	{
		s=x;
		if (s<y)
		{
		y=s;
		}
	}
}

cout<< "The second smallest number is: " << y << endl;
cin.get();

	return (0);
}

Problem is that s equals zero, and even if I change that, I'm not getting the result I wanted :)

Can any of you guys give me some advice, this is just something that I'm trying out for myself and is not evening school related :!:

Thanks,
JoBe

I haven't tried the code myself, but at a quick glance, I'd say that you need something like this:

if (x < s)
   s = x;
else if (x < y) {
   s = y;
   y = x;
}

Greetings,

The algorithm may be off in some ways. I put some prints in the code to see what was failing or skipping and nothing showed up. Firstly the reason that your check of (x<s) will never pass unless x is less that 0. Since s is initialized to 0, x will have to live up to s's expectations.

- Stack Overflow

Darn. I got it wrong.
It's more like this:

if (x < s) {
   y = s;
   s = x;
} else if (x < y) {
   y = x;
}

Hi guys,

Thanks for the quick responce, it was a combination of both, using your selection gallas and setting the variable s to 100 solved the problem.

Thanks guys, I don't suppose it would work without s being given a certain value that is equal to x :?:

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.