Chapter 2: Variables & Arithmetic
Variables & Arithmetic
Outline
Learn about variable types and how to
declare variables
Learn how to display variable values
Learn about the integral data types
Learn how to use standard binary arithmetic
operators
Learn how to use shortcut arithmetic
operators
Learn about the Boolean data type
Learn about floating-point data types
Learn how to format floating-point values
Learn about numeric type conversion
Learn about the char data type
Learn about the string data type
Learn how to define named constants
Learn how to accept console input
Variable
A variable is nothing but a name given to a
storage area that our programs can
manipulate.
Each variable in C# has a specific type,
which determines the size and layout of the
variable's memory the range of values that
can be stored within that memory and the set
of operations that can be applied to the
variable.
The basic value types provided in C# can be
categorized as:
Defining Variables
Syntax for variable definition in C# is:
<data_type> <variable_list>;
Some valid variable definitions are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
Using the Standard Binary
Arithmetic Operators
The five most commonly used binary arithmetic
operators
7
Using the Standard Binary
Arithmetic Operators
When you divide two integers (using the
division operator or the modulus operator),
the result is ALWAYS an integer
Operator precedence refers to the order in
which parts of a mathematical expression are
evaluated
8
Using Shortcut Arithmetic
Operators
C# provides you with several shortcut ways to count
and accumulate
– Examples of Shortcuts:
+=, -+, *=, /=
The prefix and postfix operators can also provide a
shorthand way of writing operators
– Examples of the unary operators:
++val, val++
Besides the prefix and postfix increment operators,
you can also use a decrement operator (--)
9
Using the Boolean Data Type
Boolean logic is based on true or false comparisons
Boolean variables can hold only one of two values:
true or false
You can assign values based on the result of
comparisons to Boolean variables
10
Using Floating-Point Data Types
A floating-point number is one that contains
decimal positions
C# supports three floating-point data types: float,
double, and decimal
A double can hold 15 to 16 significant digits of
accuracy
Floating-point numbers are double by default
11
Formatting Floating-Point Values
Standard numeric format strings are strings of
characters expressed within double quotation marks that
indicate a format for output. For example, “F3” , where F
is the format specifier and 3 is the precision specifier,
indicates a fixed point with three significant digits.
The format specifier can be one of nine built-in format
characters
The precision specifier controls the number of
significant digits or zeros to the right of the decimal point
12
Formatting Floating-Point Values
13
Understanding Numeric Type
Conversion
In arithmetic operations with variables or constants of the
same type, the result of the operation usually retains the
same type
- For example, an integer type added to another
integer type will result in an integer type
When an arithmetic operation is performed with dissimilar
types, C# chooses a unifying type for the result and
implicitly converts the nonconforming operands to the
unifying type
There are rules followed by C# for implicit numeric
conversions
14
Understanding Numeric Type
Conversion
When you perform a cast, you explicitly override
the unifying type imposed by C#
For example:
double balance = 189.66;
int dollars = (int)balance;
A cast involves placing the desired resulting type in
parentheses followed by the variable or constant to
be cast
15
Using the char Data Type
The char data type is used to hold a single character
(‘A’,’b’,’9’)
A number can be a character only if it is enclosed in
a single quotation mark (char aChar = 9; is illegal)
You can store any character in a char variable,
including escape sequences
Characters in C# are represented in Unicode
16
Using the char Data Type
Common Escape Sequences
17
Using the string Data Type
In C# the string data type holds a series of
characters
Although you can use the == comparison operator
with strings that are assigned literal values, you
CANNOT use it with strings created through other
methods
C# recommends that you use the Equals() and
Compare() methods to compare strings
A string is considered greater than another string
when it is greater lexically
18
Using the string Data Type
19 Program that compares two strings using ==
Using the string Data Type
Output of CompareNames1 program that uses ==
20
Using the string Data Type
Program that compares two strings using Equals() and
Compares()
21
Using the string Data Type
Output of CompareNames2 program that uses Equals()
and Compare()
22
Defining Named Constants
A named constant is an identifier whose contents
cannot change
You create a named constant using the keyword
const
Programmers usually name constants using all
uppercase letters, inserting underscores for
readability
Often times, constant statements are self-
documenting
23
Defining Named Constants
SalesTax program
24
Defining Named Constants
Output of SalesTax program
25
Accepting Console Input
A program that allows user input is an interactive
program
The Console.ReadLine() method accepts user input
from the keyboard
This method accepts a user’s input as a string
You must use a Convert() method to convert the
input string to the type required
26
Accepting Console Input
27
InteractiveSalesTax program
Accepting Console Input
Output of InteractiveSalesTax program
28
Accepting Console Input
Typical run of InteractiveAddition program
29
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 System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorldProgram
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("What Up Class!");
int nStop = Console.Read();
}
}
}
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
Console.Write/Console.WriteLine
Simple format for a single variable:
– Console.WriteLine (Variable Name)
Also
– Console.WriteLine (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;
– Console.WriteLine ("{0} Feet = {1} Inches",nFeet,nInches);
Console Write Statement Examples
Reading information in from the
outside world (Console.ReadLine())
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 = Console.ReadLine();
– int nNumber = int.Parse(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;
}
Console.WriteLine("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;
Console.WriteLine("Available Tickets={0}", AvailableTickets);
}
}