Home > Mobile >  A program that gets 3 digits and outputs the smallest one in C# Console App
A program that gets 3 digits and outputs the smallest one in C# Console App

Time:11-09

How can I make a program in C# that gets 3 digits from the user and outputs the smallest one? It's gonna be as a Console App.

I tried this and gave me an error (I may be stupid):

if (a<b<c)
{
min=a;
Console.WriteLine("Min: "   min);

I don't now what else should I do, I'm new to C#.

CodePudding user response:

There's nothing wrong with being new, and you aren't stupid just because you aren't sure how something works.

Think of it like this:

We need to have a variable to hold this minimum value:

int min;

First, you need to compare two values to get the smallest between them:

if (a < b)
    min = a;
else
    min = b;

Now that you have the minimum between those two, compare that value to your third input:

if (c < min)
    min = c;

If c is less than the current min value, you adjust to c, otherwise you already had your minimum value in the first comparison.

Here is a full example for you to play with as well:

int a = 4;
int b = 2;
int c = 1;

int min;

if (a < b)
    min = a;
else
    min = b;

if (c < min)
    min = c;

Console.WriteLine("Lowest value is {0}", min);

CodePudding user response:

Try this.

if (a < b && a < c)
{
    Console.WriteLine("Min: "   a);
}
else if (b < c)
{
    Console.WriteLine("Min: "   b);
}
else
{
    Console.WriteLine("Min: "   c);
}

CodePudding user response:

you cannot have several < in one condition.

For that you need to create a List, then take the minimal value : Considering that your code already converted to int :

List<int> listInt = new List<int>{a,b,c};
int min = listInt.Min(x=>x);
Console.WriteLine("Min: "   min);
  •  Tags:  
  • c#
  • Related