patterncsharpMinor
Returning the lowest and highest number based on input
Viewed 0 times
thenumberlowestinputreturningbasedhighestand
Problem
This simple console program prompts the users for a number and returns the lowest and highest numbers from their inputs. It is difficult to add more user inputs, though. How can I make this easier to maintain and extend?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int num1 = 0, num2 = 0, num3 = 0;
Console.WriteLine("lowest");
Console.WriteLine("input 1st number");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("input 2nd number");
num2 = int.Parse(Console.ReadLine());
Console.WriteLine("input 3rd number");
num3 = int.Parse(Console.ReadLine());
Console.WriteLine("input 4th number");
num4 = int.Parse(Console.ReadLine());
Console.WriteLine("input 5th number");
num5 = int.Parse(Console.ReadLine());
Console.Clear();
int lowest = ((num1 num2 ? num1: num2) > num3 ?
(num1 > num2 ? num1 : num2) : num3) ;
Console.WriteLine(" lowest is {0} ", lowest);
Console.WriteLine(" highest is {0} ", highest);
Console.ReadLine();
}
}
}Solution
If you are only worried about showing
This program will print min and max, until a non-digit character is given.
Min and Max, and nothing else is the desired result then why not use an immediate calculation approach like this? It surely does not store unnecessary inputs - using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int max = Int32.MinValue, min = Int32.MaxValue;
int value = 0;
while (int.TryParse(Console.ReadLine(), out value))
{
max = Math.Max(max, value);
min = Math.Min(min, value);
Console.WriteLine(" lowest is {0} ", min);
Console.WriteLine(" highest is {0} ", max);
}
}
}
}This program will print min and max, until a non-digit character is given.
Code Snippets
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int max = Int32.MinValue, min = Int32.MaxValue;
int value = 0;
while (int.TryParse(Console.ReadLine(), out value))
{
max = Math.Max(max, value);
min = Math.Min(min, value);
Console.WriteLine(" lowest is {0} ", min);
Console.WriteLine(" highest is {0} ", max);
}
}
}
}Context
StackExchange Code Review Q#56838, answer score: 4
Revisions (0)
No revisions yet.