This lesson will focus on basic math functionality in C# as well as user input via the console. At the end of this lesson you should be able to:
Until now we've used hardcoded values to output information to the screen. Now we'll use math on those values to force the computer to perform some mathematical grunt work. A computer uses the same laws for math as we do. The C# language follows the rule ofPEDMAS (orBEDMAS depending on your high school teacher). PEDMAS stands forParenthesis,Exponents,Division,Multiplication,Addition andSubtraction. The operations on the left are executed before the operations to the right.
Example: 3 + (4 + 5) * 2First step (Parenthesis): 3 + 9 * 2Second step (Multiplication): 3 + 18Last step (Addition): 21
Following the law of PEDMAS ensures that every computer (and human) will get a consistent answer. With that in mind, it is now possible to unleash mathematical operations on the computer.
| Type | Syntax | Example |
|---|---|---|
| Multiplication | var1 * var2 | x = 2 * 3; // x = 6 |
| Division | var1 / var2 | x = 12 / 4; // x = 3 |
| Addition | var1 + var2 | x = 2 + 1; // x = 3 |
| Subtraction | var1 - var2 | x = 3 - 6; // x = -3 |
| Parenthesis | ( ... ) | x = ( 2 + 4 ) / 3; // x = 6 / 3 = 2 |
| Modulus (Remainder) | var1 % var2 | x = 3 % 2; // x = 1 |
usingSystem;namespaceMathExampleOne{classProgram{staticvoidMain(string[]args){doublepi=3.14159;doubleradius=2.5;doublearea=pi*radius*radius;Console.WriteLine("The area of a circle with radius "+radius+" is "+area);Console.WriteLine("Hit any key to end...");Console.ReadKey();}}}
The area of a circle with radius 2.5 is 19.6349375Hit any key to end...
doublepi=3.14159;doubleradius=2.5;
Here we've assigned a value for the constant Pi. Pi is required for finding the area of a circle. We've also assigned a constant value for the radius of the circle.
doublearea=pi*radius*radius;
Here is where the computer gets to work number crunching. The area of a circle is given as A = pi * r * r. The result of the calculation will be stored in a variable namedarea.
Console.WriteLine("The area of a circle with radius "+radius+" is "+area);
We now output the result of the calculations to the console. As a bonus, we've also output the radius on the circle.
Console.WriteLine("Hit any key to end...");Console.ReadKey();
These lines of code pause the execution of the program. Without these lines the program would terminate very quickly, and we wouldn't be able to view the program output. Console.ReadyKey() waits until the user presses a key.
A programmer can request the user to input a value in the console. The easiest method to read from the console is to read the console input until the user hits theenter button. A line must be stored in a C# type called astring. A string contains a list ofchars. This string must then be converted to thetype that was requested by the program. The best way to learn is by example and by doing, so here are some examples of reading a string and then converting that string to another data type.
stringvar=Console.ReadLine();// stores the users input into a stringdoubleradius=double.Parse(var);// converts the string into a double using the Parse method
doubleradius=double.Parse(Console.ReadLine());// same as the previous method
intvalue=int.Parse(Console.ReadLine());// converts to an integer instead of a double
floatvalue=float.Parse(Console.ReadLine());// converts to a float
Each C# data type has a method to parse a string, and convert that string into the corresponding data type. The problem however is that the user might make a mistake an enter a string thatcannot be parsed. An example would be if the program requested an integer value, but the user entered a floating point value. The program will then throw an error that theInput string was not in a correct format. For now we will assume that the user will always enter the correct values, and the error that was generated will be handled in a later lesson on try, catch() and finally.
usingSystem;namespaceVariablesExampleTwo{classProgram{staticvoidMain(string[]args){doublepi=3.14159;Console.Write("Please enter a value for the radius: ");doubleradius=double.Parse(Console.ReadLine());doublearea=pi*radius*radius;Console.WriteLine("The area of a circle with radius "+radius+" is "+area);Console.WriteLine("Hit any key to end...");Console.ReadKey();}}}
Please enter a value for the radius: 2.5The area of a circle with radius 2.5 is 19.6349375Hit any key to end...
Console.Write("Please enter a value for the radius: ");doubleradius=double.Parse(Console.ReadLine());
First we prompt the user for a value. This ensures that the user realizes that the program is waiting for input. Then we read adouble into the variable namedradius. This radius is used to compute the area of the circle. Note that this program will not deal with any errors that could be generated by the Parse() method.
C# has many more math functions stored in the Math namespace. Exploration of the entire Math namespace is beyond the scope of this lesson, but many online references are available. We're going to modify the circle program to use the Math namespace where appropriate.
usingSystem;namespaceVariablesExampleThree{classProgram{staticvoidMain(string[]args){Console.Write("Please enter a value for the radius: ");doubleradius=double.Parse(Console.ReadLine());doublearea=Math.PI*Math.Pow(radius,2);Console.WriteLine("The area of a circle with radius "+radius+" is "+area);Console.WriteLine("Hit any key to end...");Console.ReadKey();}}}
Please enter a value for the radius: 2.5The area of a circle with radius 2.5 is 19.6349540849362Hit any key to end...
doublearea=Math.PI*Math.Pow(radius,2);
Notice that there is no longer a line to store a value of pi. The Math namespace already contains a definition of PI (which is much more accurate than the previous version). The Math namespace also has a method for computing powers. radius^2 is represented quite a bit easier with the Math namespace. It would also become very unwieldy to write something like radius^20 with the method that we were using in the previous examples.
| Topics inC# | ||
| Beginners | Intermediate | Advanced |
|---|---|---|
| Part of theSchool of Computer Science | ||