Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the biggest and smallest number with only with exactly three IF statements(no else)

Firstly thank you for showing interest in my question, right now I’m in my first year of being an IT assistant and this question was in our book but nobody out of my class seems to be able to find a solution for it. We aren’t allowed to use any else statements or arrays.

This was my (not working) piece of code:

double n1, n2, n3, biggest, smallest;
Console.Write("First number:  ");
n1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Second number: ");
n2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Third number: ");
n3 = Convert.ToInt32(Console.ReadLine());
if (n1 < n2 && n2 < n3)
{
    smallest = n3;
    biggest = n1;
}
if (n2 < n3 && n3 < n1)
{
    smallest = n1;
    biggest = n2;
}
if (n3 < n1 && n1 < n2)
{
    smallest = n2;
    biggest = n3;
}
Console.WriteLine("\tMax: {0}", biggest);
Console.WriteLine("\tMin: {0}", smallest);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Start with presumption that first numbers are biggest and smallest. Then check 3 possible cases where presumption was wrong…

double n1, n2, n3, biggest , smallest;
Console.Write("First number:  ");
n1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Second number: ");
n2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Third number: ");
n3 = Convert.ToInt32(Console.ReadLine());

biggest = n1;
smallest = n2;

if (n1 < n2 )
{
    smallest = n1;
    biggest = n2;
}
if (n3 < smallest)
{
    smallest = n3;
}
if (n3 > biggest )
{
    biggest = n3;
}
Console.WriteLine("\tMax: {0}", biggest);
Console.WriteLine("\tMin: {0}", smallest);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading