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

Time:09-27

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);

CodePudding user response:

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);
  •  Tags:  
  • c#
  • Related