C# Programming Tutorial: Introduction - #2 - Variables, Arithmetic Operators, and Keywords
Welcome back to the second edition of my C# programming tutorials. This time we are going to look at variables, arithmetic operators, and keywords to build a simple Fahrenheit to Celsius convertor using the formula °C = (5/9)(°F – 32) to print a conversion table to the console, so let’s get started.
The program itself still contains the Main() method, as you would expect of you remember last time, however it no longer prints out “hello, world!”, this new program may be longer however will nicely introduce the concepts that I would like to discuss in this tutorial. This program also includes some surprises that were not mentioned in the title these are comments, loops, and formatted output (you may have heard this being called “String Interpolation”)
using System;
class SecondProgram
{
/* print Fahrenheit to Celsius table between lower and upper
incrementing in steps given by step variable */
public static void Main()
{
int fahr, cel;
int lower = 0; //lower limit of temp table
int upper = 300; //uppr limit of temp table
//step size
int step = 20;
fahr = lower;
while(fahr <= upper)
{
cel = 5 * (fahr - 32) / 9;
Console.WriteLine($"{fahr} | {cel}");
fahr += step;
}
Console.ReadLine();
}
}
The two lines:
/* print Fahrenheit to Celsius table between lower and upper
incrementing in steps given by step variable */
Are a comment. This is code that the C# compiler and IDE mostly just ignore and can be used to explain what different parts of a program can do with a small explanation. There are two examples of comments in this program; the multiline comment and the single line comment. These two types can be identified by the characters that start them, and in the case of the multiline comment that end them. So, comments starting with /* and ending with */ are multiline comments this style of comment will cause all the text in-between the opening and closing symbols to be a comment, this style of comment can occur without affecting the code in any position where space or tab character could also be placed. The second type of comment we will talk about is the single line comment, this starts with // and causes everything on the line that it is defined to become a comment beyond the //. To end this style of comment all you have to do is move to the line below. Both of these types of comments are fine to use wherever you feel like, so add them whenever and wherever you feel necessary as they can only help you.
Now moving on let’s talk about the variables and the keywords relating to them. In C# all variables must be declared somewhere before they are used, most declarations occur at the top of a class or at the top of a method, except in some special circumstances that we will cover later, due to the way C# is compiled and run this is not necessary and you can put your declarations at the bottom of a method or class however conventions dictate that they go at the top, so to save the embarrassment of Code Review Stack Exchange laughing at you for putting your declarations at the bottom just put them at the top.
Now a variable declaration is always constructed of two components and the third is optional and can be done later, again except in a special circumstance that we will again cover later. The two required features of a variable declaration are, the data type keyword and the variable name or list of variable names separated by commas. The third optional part is giving the variable a value. The different methods of defining variables are outlined below.
int foo, bar;
int foo = 1, bar = 2;
int foo;
int foo = 1;
First, we define the type of data the variable is going to hold, this word before the variable is called a keyword. That means the C# compiler treats this word with a special meaning. In this example, we are setting our variables to be of type int, and int is short for integer or whole number. This is called a basic data type, the other basic types are:
- char - a single character
- short - A short int
- long - Long int
- float - floatig point number (A decimal number)
- double - Double precision float
We will talk about the sizes of each of these different types later as mentioned in the previous tutorial this first section of to get you to start coding and not bogged down in the details, Classes can also be used as data types however this is something that we will talk about when we discus classes. At the bottom of this section is a list of all of the keywords that can be used as variable types.
All the data type keywords can also be preceded by the keywords public, private, and static
- public - Can be Acessed from another class
- private - Can only be accessed from within the class or method it is defined within
- static - Means the variable will not be instanced (we will talk about instanceing later when we come to classes)
Now we define the variable name, as you can probably tell you can use any name for a variable with any character, the only caveats to this are that they may not start with a number, they cannot contain semicolons, colons, open/closing brackets, slashes, any arithmetic operator, and may not be a keyword (this last one is most of the time however it is frowned upon to use this feature). The name must also be unique from within the same scope, within the same class and/or method depending on where it is defined.
The variable can also optionally be given a value when defined this value must be of the same type, or can be cast to the same type, and the type the variable is defined as e.g. if you make a string variable you can’t assign it an int value because that would be silly.
List of data type keywords
- bool - A true or false value
- byte - A single byte of data
- int - Can only store whole numbers
- short - A short int
- long - A long int
- float - Can store a decimal number
- double - Can store double the max value of a float
- decimal - Used in finacial calculations, stored and treaded differently than float and double so has a larger processing overhead
- sbyte - Can store negative bytes
- uint - A positive value only int
- ulong - A positive value only long int
- char - A single character
- string - A sequence of characters
Now let’s get into the actual computation of the program since we have finished defining our variables. As each line of the output table is computed in the same way we can use a loop.
A loop is a block of code that is executed until the condition that sustains it becomes false. In this condition, we are using a while loop a while loops condition is defined in between the brackets after the while keyword. Our while loop:
while(fahr <=upper)
Will execute until the fahr variable is greater than or equal to the uppr variable. The while loop executes by checking the condition on the brackets, if the result of the condition is true then it will execute the code block within its {}, it will then return to the top check the condition and repeat until the condition is false, this does mean however that the while loop as a chance of not executing even once if the fahr is >= upper on the first run, this can be a problem in some situations so the do while loop also exists and we will discuss that later to. A body, or code block, of a while loop can be one or more statements as long as it is enclosed within {}.
Now the meat of the program is executed within the while loop, first the Celsius conversion takes place. This conversion is done all in one statement as shown here:
cel = 5 * (fahr - 32) / 9;
The reason for multiplying be 5 then dividing by 9 is because this is all int maths and link many other programming languages C# truncates the decimal part of an int division so 5/9 with int maths would result in 0 and 0 times anything is just 0 so to keep things working we more the order around to give us the current value. Of course, you can convert all of this to float maths for greater precision if you want. Here the value of fahr is not changed as no = sign is used on the fahr variable so its stored value does not change its current value in the equation however does. This is much like how you would use variables in algebra. A full list of arithmetic operators can be found at the bottom of this section.
List of Arithmetic Operators
- = - Sets the expression on the left equal to the expression on the left
- + - Adds the expression on the left to the expression of the right
- - - Subtracts the expression on the the right from the expression on the left
- / - Divides the expression on the left by the expression on the right
- * - Multiplys the expression on the left by the expression the right
- % - Returns the remander from divideing the expression on the left by the expression on the left
- << - Bitshift the expression on the right by the expression on the left to the left
- >> - Bitshift the expression on the right by the expression on the left to the right
Next, we print the value of the conversion and the current fahr value to the console here
Console.WriteLine($”{fahr} | {cel}”);
We have already seen Console.WriteLine() in the previous tutorial so we are not going to go over that gain but the method by which we are putting the variable into the string we are. This is called string interpolation and is a more readable version of what you will see in most tutorials about this subject, as in other programming languages and most other tutorials will have you type:
Console.WriteLine(fahr + “ | “ + cel);
This method of adding variables into a string is still available in C# however introduced in C# 6.0 was string interpolation. This is the method we are using in our program; to use it you must place a $ before the opening “ of the string then within the string you can put code contained in {} that will return something and its value will be converted into a string with the returned value replaceing whatever is within the {}. This allows us to very simply output data as text in a very easy to understand and concise manor.
Finally, in the while loop we increment the fahr variable by saying:
fahr += step;
This again is different to how you will see many beginner tutorials tell you to increment a variable as they will say type:
fahr = fahr + step;
However my method means the same thing, you type less, and it is a useful feature of C# so no reason to hide it from you. All this line does is take the current value of fahr adds the step value then set that to be the new value of the fahr variable.
After the incrementing the while loop runs gain until the condition is false.
Now that is all we have for today I will leave you with some exercises to attempt. The answers will be in the dropdown. As always, I hope you enjoyed this tutorial and hope to see you next time.
Exercise 1: Modify the Celcius to Fahrenheit convertor to use floating point maths
This task is very simple all you need to do is change the int keyword to a float keyword
...
public static void Main()
{
float fahr, cel;
float lower = 0;
float upper = 300;
float step = 20;
fahr = lower;
...
Exercise 2: Modify the Celcius to Fahrenheit convertor to print a table heading above the conversion table
Add this line above the while loop and it will print the table headings
...
fahr = lower;
Console.WriteLine("Fahrenheit | Celcius")
while(fahr <= upper)
{
cel = 5 * (fahr - 32) / 9;
Console.WriteLine($"{fahr} | {cel}");
fahr += step;
}
...
Exercise 3: Create the corrisponding Fahrenheit to Celcius convertor
Rewrite the same program with the equation re-arranged like this: °F = ((°C * 9) / 5) + 32
using System;
class Exercise3
{
public static void Main()
{
int fahr, cel;
int lower = 0;
int upper = 300;
int step = 20;
cel = lower;
while(cel <= upper)
{
fahr = ((cel * 9) / 5) + 32;
Console.WriteLine($"{cel} | {fahr}");
cel += step;
}
}
}
Back To Collection | Previous | Next