C Sharp PPT Ch03
C Sharp PPT Ch03
Variables, Constants
and Calculations
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-3
Data – Variables and Constants - 1
• Variable
– Memory locations that hold data that can
change during project execution
• Example: Customer's name
• Constant
– Memory locations that hold data that cannot
change during execution
• Examples: Company name or sales tax rate
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-4
Data – Variables and Constants - 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-5
Data – Variables and Constants - 3
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-6
Data Types - 1
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-7
Data Types - 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-8
Naming Rules
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-10
Constants: Named and Intrinsic
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-11
Named Constants - 1
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-12
Named Constants - 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-13
Assigning Values to Constants - 1
• Numeric constants
– May contain only digits (0-9)
– Decimal point
– Sign at the left side (+ or -)
– Type declaration character at the right side (optional)
– Cannot contain comma, dollar sign, any other special
characters, sign (+ or -) at right side
– Use type declaration character to specify the data
type decimal M or m
• Without type declaration character, double D or d
whole numbers assumed to be int long L or l
and fractional values assumed to be short S or s
double float F or f
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-14
Assigning Values to Constants - 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-15
Intrinsic Constants
• System-defined constants
• Declared in system class libraries
• Specify class name or group name and
constant name
– Example – Color.Red is the constant “Red” in
the class “Color”
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-16
Declaring Variables - 1
• Declare a variable
– Specify data type and follow with an
identifier
– Assign an initial value (optional)
string customerNameString;
string customerNameString = “None”;
private int totalSoldInteger;
int totalSoldInteger = 0;
float temperatureFloat;
float temperatureFloat = 32f;
decimal priceDecimal;
private decimal priceDecimal = 99.95m;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-17
Declaring Variables - 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-18
Initializing Numeric Variables
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-19
Entering Declaration Statements
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-20
Scope and Lifetime of Variables
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-21
Variable Lifetime
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-22
Local Declarations
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-23
Class-Level Declarations
Class variables
and constants
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-24
Calculations
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-25
Converting Strings to a Numeric Data Type
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-27
Converting to String
Operator Operation
+ Addition
– Subtraction
Multiplication
/ Division
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-29
Arithmetic Operations - 2
• Modulus (%)
– Returns the remainder of a division operation
// Assume that totalMinutesInteger = 150
minutesInteger = totalMinutesInteger % 60;
// Result is 30.
// (150 divided by 60 is 2 with a remainder of 30.)
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-30
Arithmetic Operations - 3
• Division (/)
– Divide fractional values or integers
– If at least one value is fractional, the result is
fractional
– If both values are integer, the result is integer
(any remainder is dropped)
// Assume that minutesInteger = 150
// Integer division.
hoursInteger = minutesInteger / 60; // Result is 2.
// Fractional division.
hoursFloat = minutesInteger / 60.0f; // Result is 2.5.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-31
Arithmetic Operations - 4
• Exponentiation
– C# does not have an operator for
exponentiation
– Use Math.Pow
• See Appendix B for Math methods
• See Chapter 5 for an example
– “Writing a Method with Multiple Arguments”
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-32
Order of Operations - 1
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-33
Order of Operations - 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-34
Order of Operations - 3
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-35
Using Calculations in Code
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-36
Assignment Operators
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-37
Increment and Decrement Operators
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-38
Converting between Numeric Data Types - 1
• Implicit conversions
– Converts value from narrower data type to a wider
type when there is no danger of losing precision
• Note: C# has no implicit conversions to convert from decimal
From To
byte short, int, long, float, double, decimal
short int, long, float, double, decimal
int long, float, double, decimal
long float, double, decimal
float double
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-39
Converting between Numeric Data Types - 2
• Explicit conversions
– Also called casting
– Convert between data types without implicit
conversions
– Specify the destination data type in
parentheses before the data value to convert
– Generates an exception if significant digits will
be lost
numberDecimal = (decimal) numberFloat;
valueInt = (int) valueDouble;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-40
Converting between Numeric Data Types - 3
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-41
Performing Calculations with
Unlike Data Types
• C# performs the calculations using the wider
data type
• Perform a cast if you want to convert the result
to a different data type
(int) countInteger / numberDecimal
(float) countInteger / numberDecimal
• C# does not convert to a different data type until
necessary
countInteger / 2 amountDecimal
– Division produces an integer intermediate result; then
multiplication produces a decimal result
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-42
Rounding Numbers
• Round decimal fractions using decimal.Round
– Returns a decimal result rounded to the specified number of
digits
// Round to two decimal positions.
resultDecimal = decimal.Round(amountDecimal, 2);
• decimal.Round and Convert methods use "rounding
toward even" if the digit to the right of the final digit is
exactly 5.
Number of decimal
Decimal value to round Result
positions
1.455 2 1.46
1.445 2 1.44
1.5 0 2
2.5 0 2
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-43
Formatting Data for Display
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-45
Using Format Specifier Codes - 2
• Additional Format Specifier Codes
– "F" or "f" – Fixed point
• String of numeric digits, no commas, two decimal places,
minus sign at left for negative values
– "D" or "d" – Digits
• Force a specified number of digits to display
• For integer data types only, minus sign at left
– "P" or "p" – Percent
• Multiplies the value by 100, adds a space and a percent sign,
rounds to two decimal places
– Additional codes for dates and times
• d, D, t, T, f, F, g, G, m, M, r, R
• Date and time codes are case sensitive
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-46
Choosing the Controls
for Program Output
• Output can display in labels or text boxes
– Labels – Cannot be changed by the user
• Used traditionally for program output
– Text boxes – Can be changed by the user
• To use for output
– Set ReadOnly property to true (BackColor property changes to
Control)
– Set TabStop property to false
– Set BorderStyle property to Fixed3D or FixedSingle
• Advantages over using labels for output
– Text boxes do not disappear when cleared
– Form layout looks more uniform
– The clipboard Copy command is available to the user
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-47
Format Specifier Code Examples
Format Specifier
Variable Value Output
Code
totalDecimal 1125.6744 "C" $1,125.67
totalDecimal 1125.6744 "N" 1,125.67
totalDecimal 1125.6744 "N0" 1,126
balanceDecimal 1125.6744 "N3" 1,125.674
balanceDecimal 1125.6744 "F0" 1126
pinInteger 123 "D6" 000123
rateDecimal 0.075 "P" 7.50 %
rateDecimal 0.075 "P3" 7.500 %
rateDecimal 0.075 "P0" 8%
valueInteger –10 "C" ($10.00)
valueInteger –10 "N" – 10.00
valueInteger –10 "D3" – 010
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-48
Handling Exceptions
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-49
try/catch Blocks
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-50
The try Block – General Form
• try
• {
• // Statements that may cause error.
• }
• catch [(ExceptionType [VariableName])]
• {
• // Statements for action when exception occurs.
• }
• [finally
• {
• // Statements that always execute before exit of try
block.
• }]
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-51
The try Block - Example
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-54
Handling Multiple Exceptions - 1
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-55
Handling Multiple Exceptions - 2
catch (FormatException theException)
{
// Statements for nonnumeric data.
}
catch (ArithmeticException theException)
{
// Statements to handle calculation problem.
}
catch (Exception theException)
{
// Statements for any other exception.
}
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-56
Displaying Messages in Message Boxes
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-57
The MessageBox Object –
General Form
• Arguments must match one of the formats
• Do not reverse, transpose or leave out any
argument
MessageBox.Show(TextMessage);
MessageBox.Show(TextMessage, TitlebarText);
MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons);
MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons, MessageBoxIcon);
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-58
The TextMessage String
• TextMessage String
– String literal enclosed in quotes
– String variable
– May concatenate several items
• i.e. Combine a literal with a variable value
– If message is too long, will wrap to next line
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-59
The Titlebar Text
• TitlebarText
– Appears in the title bar of message box
– If no TitlebarText argument, title bar will
appear empty
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-60
MessageBox Buttons
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-61
MessageBoxIcon
• IntelliSense pops up with complete list
• Constants for MessageBoxIcon
– Asterisk
– Error
– Exclamation
– Hand
– Information
– None
– Question
– Stop
– Warning
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-62
Using Overloaded Methods
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-64
Nested try/catch Blocks - 1
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-65
Nested try/catch Blocks - 2
try // Outer try block for the first field.
{
// Convert first field to numeric.
try // Inner try block for the second field.
{
// Convert second field to numeric.
// Perform the calculations for the fields that passed conversion.
}
catch (FormatException secondException)
{
// Handle any exceptions for the second field.
// Display a message and reset the focus for the second field.
}
// End of inner try block for the second field.
}
catch (FormatException firstException)
{
// Handle exceptions for the first field.
// Display a message and reset the focus for the first field.
}
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-66
Counting & Accumulating Sums
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-67
Summing Numbers
totalAmountDecimal += amountDecimal;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-68
Counting
int saleCountInteger;
saleCountInteger ++;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-69
Calculating an Average
averageSaleDecimal = totalAmountDecimal /
saleCountInteger;
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. 3-70