Goal: Ask for user input with C# Console and use that input to compute an average

Difficulty: Easy

Prerequisites: Visual Studios or other C# Compiler

Often times it is useful to be able to take in user input. While Console Applications in C# are by far the simplest development platform you can built on. In fact even when I'm building more complex applications I'll often write methods in a console app to test first and then port them over. But in order to do any of this we need to leverage the Console.ReadLine() function.

The simple example of how to find the average of any given set of numbers is a great way to practice! First lets go over the basics: You can easily store your Console.ReadLine() value into a variable, however it should be noted that Console.ReadLine takes in a string, and so it must be typecasted in order to store it in a different variable type. In the example below I'll take in two integers and writeline them back to the user:

//This code can be used to read console input into an integer variable
int myInt;
myInt = int.Parse(Console.ReadLine());

//and here we output the results of myInt to the screen
Console.WriteLine("Variable myInt = {0}", myInt);

//We can also read into an integer being declared on the fly
int mySecondInt = int.Parse(Console.ReadLine());

//and here we output the results using string concatination instead
Console.WriteLine("Variable mySecondInt = " + mySecondInt);

That's a great start to our mean finder but we want to be a little smarter and dynamic in our code writing so that we don't need to create lots and lots of Console.ReadLine calls or change our code every time we want to change the number of user inputs. To accomplish this we can use a while loop and just continue to store values into the variable we declare until the readline is blank. I am also going to be storing the total of the numbers I take in in a seperate variable, and a total number of numbers taken in. This will give me all the information I need to find the average/mean of the numbers fed to Console.ReadLine(). (Keep in mind this code isn't fool proof, if you enter a string it will not work properly).

string number;
double total = 0;
int numbers = 0;
while ((number = Console.ReadLine()) != "")
{
    total += double.Parse(number);
    numbers++;
}

Console.WriteLine("The average of the numbers entered is {0}", total / numbers);

You can see that by using a while loop with our Console.ReadLine we were able to cut down on the amount of code we had to write, and the number of changes that will need to ever be made to the code directly. Now it can do 100 user inputs just as easily as 1 or 2.

Comments

Leave a Reply



(Your email will not be publicly displayed.)



Search