Write your question here.
For this small assignment, I have to return the second smallest number depending on the users input. The only thing I am supposed to use to solve this problem is while loops. It is supposed to be extremely basic. What I am trying to do is store the smallest number in a variable, and store the second smallest into another variable. I am sometimes getting the correct answer when I try random numbers and other time's I am not, which makes me think my code is wrong. Any help will be greatly appreciated, thank you!
#include <iostream>
#include <limits.h>
usingnamespace std;
int main () {
int a,x,y,z;
a = INT_MAX
while (cin >> y) {
if (y < a) {
x = y;
}
if (y > a) {
z = y;
}
if (z < x) {
a = z;
}
}
cout << "The second smallest number is: " << a << endl;
return 0;
}
First, the names of your variables do not tell what those variables are for.
Second, your indentation could be more expressive. As is, it is hard to see what is in the loop.
Third, your statement on line 7 lacks a semicolon.
Logically, there are three possibilities when a new value comes in:
1. The value is the new smallest. Therefore, the previous smallest is now second smallest. Both smallest and second do update.
2. The value is not new smallest, but still smaller than the current second. The second must update.
3. Neither needs update.
int main() {
int lowest, second_lowest, input;
lowest = second_lowest = INT_MAX;
input = 0;
std::cout << "Enter your numbers and enter -99 when done" << std::endl;
while (input != -99)
{
std::cin >> input;
if (input != -99)
{
if (input < lowest || input < second_lowest)
{
if (input < lowest)
{
second_lowest = lowest;
lowest = input;
}
else if (input < second_lowest && input > lowest)
{
second_lowest = input;
}
}
}
}
std::cout << "The second smallest number is: " << second_lowest << std::endl;
return 0;
}
Here is what i did. Naming variables with names that determine what they do will go a long way to making the task easier. See if this gets you going, it seems fine to me. Happy programming!