Chapter 2: Variables & Arithmetic
Variables & Arithmetic
C# Basic Structure
usings (with semi-colon)
namespace FirstProgram
{
class FirstProgram
{
static void Main(string[] args)
{
//Do some stuff
}
}
}
C# programs are collections of classes. Classes are comprised of
Attributes, Properties and Methods. One class is identified as the
"Start Up Class" for the program
Main is a method that is usually always found in the start-up class for a
program.
C# itself has really only simple math, assignment and logic statements
actually included within the language. Just about everything else is
handled by class libraries that contain additional methods.
Each command in a C# program must end with a semi-colon
Let’s "Code" the Obligatory
Hello World program
// This is traditionally the first program written.
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace HelloWorldProgram
{
class HelloWorld
{
static void Main(string[] args)
{
[Link]("What Up Class!");
int nStop = [Link]();
}
}
}
OK – That is out of the way
Let’s Move on
All programming languages are really very
similar
– Once you understand how to design and
program, it becomes more of a translation
exercise.
– But, you need to get the basics first….
Variables
A variable is a memory location whose contents may
change during program execution.
C# has two different "Types" of Variables
– Value Types – The variable represent a place in memory
that actually holds the value of the variable.
– Reference Types – The variable represents a place in
memory that holds the ADDRESS of the value of the
variable.
Variables - A Pretty Picture
Value Variable Types
The variable location IS the value
Integral Data Type
– int = Integer = 4 Bytes (+- 2 billion)
– short = Integer = 2 Bytes (+- 32K)
– long = Integer = 8 Bytes (64 bits) 16 digit precision
– char = 16 bits (2 Bytes - Unicode) - Discuss
– bool = Boolean (True/False) = (Not sure of length)
Floating Point Data Types
– Double precision (double) gives you 52 significant bits (15 digits),
11 bits of exponent, and 1 sign bit. (5.0 × 10^−324 to
1.7 × 10^308. Default for literals)
– Single precision (float) gives you 23 significant bits (7 digits), 8 bits
of exponent, and 1 sign bit. 1.5 × 10^−45 to 3.4 × 10^38 with a
precision of 7 digits. (Literals need to have "F" appended)
Value Variable Types
The variable location IS the value
Decimal Types
– New – Up to 28 digits of precision (128 bits used to represent the number)
– Decimal place can be included
But unlike Float or Decimal, there is no conversion
The Precision and the Decimal place go together
For literals, put an “M” at the end to state that the number is a decimal
Unless you really need to use very very big number or very very small numbers, suggest you
use Decimal instead of Double of Float
– But you’ll still be responsible for understanding the different!!
Boolean
– Value of either true or false
– You must use true or false, not 0, 1 or -1
Char
– Single Unicode Character (2 Bytes)
What is Unicode??
In Assignment, Single Quotes are used
– Char bChar = ‘B’;
Reference Variable Types
Remember, the Value of the variable is the
Address of the variable
– Strings
During Assignment – Double Quotes are Use
String sMyName = "Louis Bradley"
– Objects (Classes)
A Word on Variable Types
In C#
– All Variable Types are actually Classes
Which implies that when you define a variable you are
really creating an Instance of an Class
Variable/Identifier Names
Numbers, Letters (upper or lower case) and the underscore (_)
Must begin with either a letter or an underscore.
Cannot be a reserved word
Should be indicative of what the variable is storing
Capitalization Counts!!!
– Variable1, variable1 and VARIABLE1 are three different
variables!!!
Try not to use run on variable names
– costofliving – use cost_of_living or costOfLiving
– currentinterestrate – use current_interest_rate or
currentInterestRate
Constants
Constants are anything entered into a "C#" program
that cannot be changed.
– Numbers, strings
Named Constants are also unchangeable, but
instead of just being a number or string, they have a
name.
– Why would we want to do this?
Traditionally Named Constants are written in all
upper case. (Nothing is going to stop you from
mixed case. It’s just good practice!!)
Variable/Identifier Names
So, what does this program do?:
– const double a = 2.54;
– double y = 12;
– double x;
– x = y * a;
Variable/Identifier Names
What about now?
– const double CENTIMETERS_PER_INCH = 2.54;
– double centimeters = 12;
– double inches;
– inches = centimeters * CENTIMETERS_PER_INCH;
Comments and Structure
Comments add readability to the code and explain what you
are trying to do
Single Line comments begin with two slashes
//this is a line comment
Multi Line comments begin with /* and end with */
/*this is a multi-line comment
and this is line two of the comment */
Program Structure relates to the use of white space and
indentation.
– Anything within a Curly Brace should be indented
– Concepts should be separated with a blank link
– Comments should explain what you are doing
– Variable names should be indicative of what they are used for.
Reserved Words
C# has a list of "words" that cannot be used
a variable or method/class names because
they are part of the "C#" language
Ones that we know about now include:
– int, float, double, char, const, void, string
to name a few
Arithmetic Operators
+, -, /, * and % (Modulas/Remainder)
Exponentiation is a handled through method calls
/ with integral data will truncate the remainder
Standard order of precedence
– Parenthesis then
– Unary operators (-) then
– * / % from left to right then
– + - from left to right
Mixed Expressions
If all operators are the same, then that data
type will be returned.
If one operator is floating point and the other
is integral, the integral is converted (cast) to
floating point and the expression evaluated.
This is done one expression at a time in
order or precedence.
Let’s do some for practice….
Mixed Expressions
What if you don’t like the rules
casting is a feature that can change the type of data so
that the calculation performs as you want, not as the
computer wants.
(int) (expression)
calculates the expression, then drops any digits to
the right of the decimal
(double) (expression)
calculates the expression, then stores whatever the
answer is in a floating point number
Casting a Char
(int)‘A’ is 65 (the ASCII equivalent of the
symbol ‘A’
(char) 66 is ‘B’
String Type
A string is a sequence of zero or more
characters.
Strings in C# are enclosed in double quotes
– char on the other hand are enclosed in single
quotes
The character number in a string starts with 0
and goes to the length of the string -1.
Spaces count!!
String Type Concatenation
The "+" sign is used to combine strings into
longer strings
– sFirstName = "Louis";
– sLastName = "Bradley";
– sFullName = sFirstName + " " + sLastName
Syntax vs. Semantics
If the problem was to add five to two and then
multiple the sum by 3, which is correct?
int demo;
demo = 3 * 5 + 2;
demo = 3 * (5 + 2);
Assignment Statements
The stuff on the right of the "=" is completely
computed, and then put into the memory
location on the left of the "=".
Initialization
When a variable is declared, it is assigned a memory
location.
– That location probably already has stuff it in
A variable can be initialized in three different ways:
– At the same time it is declared
int nNumber = 0;
– In a separate assignment statement after it is declared
int nNumber;
nNumber = 0;
– It can be read from the console or from a file.
Displaying information to the Outside World
[Link]/[Link]
Simple format for a single variable:
– [Link] (Variable Name)
Also
– [Link] (Format String, Variable List)
Write and WriteLine do the same thing
– WriteLine includes a CRLF (Carriage Return/Line Feed) at
the end of the variables.
We can do that with an "escape sequence" as well and we’ll
talk about that later!!
Format String Syntax
The Format String is the first parameter to the
Write/WriteLine Method
It is a single string. Each set of curly brackets
represents the format of one variable (left most
variable is {0}, then {1}, etc.)
The string can also have regular text embedded
within in for context (similar to the C fprint command
– const int INCHES_PER_FOOT = 12;
– int nFeet = 3;
– int nInches = nFeet * INCHES_PER_FOOT;
– [Link] ("{0} Feet = {1} Inches",nFeet,nInches);
Console Write Statement Examples
Reading information in from the
outside world ([Link]())
Reads a String from the console and puts it
into a String variable.
Once in the variable, parsing functions can
be applied to cast the string as something
else.
– String sInput = [Link]();
– int nNumber = [Link](sInput);
Program without using NULL
coalescing operator
using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;
if (TicketsOnSale == null)
{
AvailableTickets = 0;
}
else
{
AvailableTickets = (int)TicketsOnSale;
}
[Link]("Available Tickets={0}", AvailableTickets);
}
}
The previous program is re-written
using NULL coalescing operator
using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;
//Using null coalesce operator ??
AvailableTickets = TicketsOnSale ?? 0;
[Link]("Available Tickets={0}", AvailableTickets);
}
}