Chapter 3
Variables,
Constants and
Calculations
Programming In
C Shap
Variables & Constants
• Variable
– Memory locations that hold data that can be
changed during project execution
– Ex: hours worked
• Named Constant
– Memory locations that hold data that cannot be
changed during project execution
– Ex: Sales tax percentage
3- 2
© 2009
Constants
• Named
– User defined
• Intrinsic
– System defined within Visual Studio (Example:
Color.Blue, Color.Yellow)
– In Chapter 23 we used the Intrinsic Color
Constants
3- 3
© 2009
1
Data Types
•
•
•
•
•
•
•
Boolean
Byte (0 to 255)
Char
Date
String
Decimal
Object
• Short (-32,768 to 32,767)
• Integer (-2,147,483,648 to
2,147,483,647)
• Long (larger whole numbers)
• Single (floating point accuracy
to 6 digits)
ã Double (floating point accuracy
to 14 points)
3- 4
â 2009
Data Types – Memory Usage
•
•
•
•
•
•
•
Boolean – 2 bytes
Byte – 1 byte
Char – 2 bytes
Date – 8 bytes
String – varies
Decimal – 16 bytes
Object –
•
•
•
•
•
Short – 2 bytes
Integer – 4 bytes
Long – 8 bytes
Single – 4 bytes
Double – 8 bytes
3- 5
© 2009
Data Types – Prefixes
•
•
•
•
•
•
•
3- 6
Boolean – bln
Byte – byt
Char – chr
Date – dat
String – str
Decimal – dec
Object – depends on
type of object
•
•
•
•
•
Short – sht
Integer – int
Long – lng
Single – sng
Double – dbl
© 2009
2
Declaration
• Variables and Named Constants must be
declared before being used in code
• When you declare a Variable or Named Constant
C#
– Reserves an area of memory
– Assigns it a name called an Identifier
• Declaration statements are coded either
– Beginning of a procedure
General Declarations of a module
3- 7
â 2009
Declaration Statements
ã CONST used to declare Named Constants
• Declaration includes
–
–
–
–
Name, follow Naming Convention Rules
Data Type
Required Value for Constants
Optional Initial Value for Variables
• Declare variable:
– Data_Type
– Data_Type
var_name;
var_name = init_value;
• Declare const
– Data_Type
const
const_name = value;
3- 8
© 2009
Declaration Examples
string strName, strSSN ;
int intAge;
decimal decPayRate ;
decimal decTax=0.1 ;
bool blnInsured
;
long lngPopulation ;
decimal decDT, decCD, decCR;
decimal decHour, decSumSal, decDiemTB, decSum=0;
decimal decTAX = 0.12, decHSLUONG=3.16;
Const decimal decDISCOUNT_RATE = 0.15M;
Note: Constants are named using all
uppercase letters EXCEPT the prefix.
3- 9
© 2009
3
Variables – Scope & Lifetime
• Global/Public (use sparingly and cautiously)
– Available to all modules and procedures of Project
– Initialized at start of Project
• Module/Private
(Form)
– Available to one module and all procedures within that module
– Initialized 1st time the Form is loaded
• Local
– Available only to the procedure it is declared in
– Initialized every time the Procedure runs
• Block (not used until later in this course)
– Available only to the block of code inside a procedure it is declared in
– Initialized every time the Procedure runs
3- 10
â 2009
Naming Rules (*)
ã You must follow when creating variable and constant
names
– Names can include letters, digits, and the underscore, but must
begin with a letter
– Names cannot contain spaces or periods
– Names cannot be # reserved words such as new, class, public, or
conts (keyworks)
– Names are not case sensitive
– For all intensive purposes, a Name can be as long as you want (the
actual limit is 16,383 characters in length).
3- 11
© 2009
Accessibility Domains
Keyword
Public
Private
Protected
3- 12
Description
Accessible from anywhere in the program
or from any other program
that references this one.
Accessible from anywhere inside this class.
Accessible from anywhere inside this class
or in any class that inherits from this class.
© 2009
4
Scope (Phạm vi biến)
•
Public
•
Module/Private
– Available to all modules and procedures of Project
– Must be referenced by the namespace
(Form)
– Can be used in any procedure on a specific Form, but is not visible to
other Forms
– Initialized 1st time the Form is loaded
•
Local
•
Block
– Available only to the procedure it is declared in
– Initialized every time the Procedure runs
– Available only to the block of code inside a procedure it is declared in
– Initialized every time the Procedure runs
3- 13
© 2009
Scope Declaring & Naming
• Global/Public
g prefix
– Declare in General Declarations as Public
string gstrName;
• Module/Private
m prefix
– Declare in Module’s General Declarations as Private
const decimal mdecSUADA = 2.5D;
decimal mdecSubToTal1KH, decToTalDue1KHCoThue;
int mintTongSoKH;
• Local
no prefix required
– Declare in Event Procedures
string strName
3- 14
© 2009
Declaring Local Level
Variables Example
Local Level Variables
3- 15
© 2009
5
Declaring Module Level Variables Example
Module - Level
Variables and Constants
3- 16
© 2009
Declaring Block Level Variables Example
int a,b;
Block Level Variables
if (a > b)
{
int max;
max = a;
}
Block Level Variables
else
{
int max;
max = b;
}
3- 17
© 2009
Calculations
• Calculations can be performed using
properties of certain objects, variables,
constants, and numeric literals
• Do Not use Strings in calculations
• Values from Text property of Text Boxes
– Are Strings, even if they contain numeric data
– Must be converted to a Numeric Data Type
3- 18
© 2009
6
Conversion Examples
intQuantity
decPrice
intWholeNumber
decDollars
strValue
=
=
=
=
=
Convert.ToInt32 (txtQuantity.Text)
Convert.ToDecimal (txtPrice.Text)
Convert.ToInt32(decFractionalValue)
Convert.ToDecimal(intDollars)
Convert.ToString (decValue)
Function
Name
Argument
To Be Acted Upon
3- 19
© 2009
Mathematical Operators
Operator
Operation
Addition
+
-
Subtraction
*
Multiplication
/
Division
%
Modulus (division's
remainder)
3- 20
â 2009
Mathematical Order of
Operations
ã Computers solve math formulas based on a
specific order 1st, then left to right
1.
2.
3.
4.
5.
3- 21
Parentheses
Exponentiation
Multiplication & Division
Modulus
Addition & Subtraction
© 2009
7
Mathematical Examples
• Note the use of parentheses to control
3+4*2 = 11 Multiply then add
(3+4)*2 = 14 Parentheses control: add then multiply
8/4*2 = 4
Same level, left to right: divide then multiply
3- 22
© 2009
Mathematical Examples
Thứ tự thực hiện
3- 23
© 2009
Mathematical Examples
Thứ tự thưc hiện
3- 24
© 2009
8
Handling Exceptions
• Exceptions occur when user enters
unexpected/invalid data and program code
does not anticipate this possibility, such as
– User enters nonnumeric data in Text Box and
code attempts to run a Numeric Conversion
Function
– User enters data that results in division by zero
3- 25
â 2009
Try/Catch Blocks
ã Used to catch and handle exceptions;
referred to as error trapping or handling
• Enclose statements that might cause an
error within Try/Catch Block
– If an error occurs control is transferred to the
Catch Block
3- 26
© 2009
Try Block - General Form
Try
{
statements that may cause error
}
catch [ExceptionType VariableName ]
{
statements for action when an exception occurs
}
3- 27
© 2009
9
Try Block - Example 1
Catches All Exceptions
try
{
intQuantity=CInt(txtQuantity.Text)
lblQuantity.Text=CStr(intQuantity)
}
catch
{
lblMessage.Text="Error in input data.“
// thơng thường báo qua MessageBox.Show (???)
}
3- 28
© 2009
Try Block - Example 2
Catches Specific Exception
try
{
intQuantity=CInt(txtQuantity.Text)
lblQuantity.Text=CStr(intQuantity)
}
catch (InvalidCastException MyErr )
{
lblMessage.Text="Error in input data."
}
catch (DivideByZeroException MyErr )
{
lblMessage.Text="Error chia cho không."
}
3- 29
Conversion exception, usually caused
by nonnumeric or blank data
© 2009
Try Block - Example 3
Catches Multiple Specific Exceptions
try
{
statements that may cause errors
}
catch (InvalidCastException MyErr )
{
error messages and statements for nonnumeric data
}
catch (ArithmeticException MyErr )
{
error messages and statements for calculation problems
}
catch (Exception MyErr )
{
error messages and statements for any other exception
}
3- 30
© 2009
10
MessageBox Object
• Use Show Method of MessageBox to
display special type of window
• Arguments of Show method
–
–
–
–
Message to display
Optional Title Bar Caption
Optional Button(s)
Optional Icon
3- 31
â 2009
MessageBox Syntax
ã The MessageBox is an Overloaded Method
– Overloading – ability to call different versions of a procedure
based on the number and data types of the arguments passed to that
procedure
– The number and data types of the arguments expected by a
procedure are called Signatures
– There are multiple Signatures to choose from
– Arguments must be included to exactly match one of the
predefined Signatures
MessageBox.Show (TextMessage, TitlebarText, _
MessageBoxButtons, MesssageBoxIcon)
3- 32
â 2009
MessageBoxButtons
Constants
ã
ã
ã
ã
ã
ã
3- 33
OK
OKCancel
RetryCancel
YesNo
YesNoCancel
AbortRetryIgnore
â 2009
11
MessageBoxIcon Constants
ã
ã
ã
ã
ã
Asterisk
Error
Exclamation
Hand
Information
ã
ã
ã
ã
None
Question
Stop
Warning
3- 34
â 2009
Counting & Accumulating Sums
ã Must use Module/Form level variables since
Local/Event level variables reset to 0 each time
the procedure is called
• Summing
– mdecOrderTotal = mdecOrderTotal + decItemPrice
• Counting
– mintNumItems = mintNumItems + 1
– mintNumItems += mintNumItems
• Averaging
– mdecAveSale = mdecOrderTotal / mintNumItems
3- 35
© 2009
Ví Dụ Dùng Biến Cục Bộ
private void btnCong_Click(object sender, EventArgs e)
{ int intSoA, intSoB;
Double dblKetQua;
intSoA = int.Parse(txtA.Text);
intSoB = Convert.ToInt32(txtB.Text);
dblKetQua = intSoA + intSoB;
lblKQ.Text = dblKetQua.ToString();
}
3- 36
© 2009
12
Ví Dụ Dùng Biến Cục Bộ & Try Catch
private void btnCong_Click(object sender, EventArgs e)
{
int intSoA, intSoB;
Double dblKetQua;
try
{
intSoA = int.Parse(txtA.Text);
intSoB = Convert.ToInt32(txtB.Text);
dblKetQua = intSoA + intSoB;
lblKQ.Text = dblKetQua.ToString();
}
catch (Exception MyErr)
{
MessageBox.Show("Loi chuyen kieu" + MyErr.Message, "Thơng báo lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
3- 37
© 2009
Ví Dụ: Dùng Biến Toàn Cục & Hằng Số
Dùng hằng ??
Dùng biến tồn
cục ??
3- 38
© 2009
13
Chapter 3
Variables,
Constants and
Calculations
Programming In
C Shap
Variables & Constants
• Variable
– Memory locations that hold data that can be
changed during project execution
– Ex: hours worked
• Named Constant
– Memory locations that hold data that cannot be
changed during project execution
– Ex: Sales tax percentage
3- 2
© 2009
Constants
• Named
– User defined
• Intrinsic
– System defined within Visual Studio (Example:
Color.Blue, Color.Yellow)
– In Chapter 23 we used the Intrinsic Color
Constants
3- 3
© 2009
1
Data Types
•
•
•
•
•
•
•
Boolean
Byte (0 to 255)
Char
Date
String
Decimal
Object
• Short (-32,768 to 32,767)
• Integer (-2,147,483,648 to
2,147,483,647)
• Long (larger whole numbers)
• Single (floating point accuracy
to 6 digits)
ã Double (floating point accuracy
to 14 points)
3- 4
â 2009
Data Types – Memory Usage
•
•
•
•
•
•
•
Boolean – 2 bytes
Byte – 1 byte
Char – 2 bytes
Date – 8 bytes
String – varies
Decimal – 16 bytes
Object –
•
•
•
•
•
Short – 2 bytes
Integer – 4 bytes
Long – 8 bytes
Single – 4 bytes
Double – 8 bytes
3- 5
© 2009
Data Types – Prefixes
•
•
•
•
•
•
•
3- 6
Boolean – bln
Byte – byt
Char – chr
Date – dat
String – str
Decimal – dec
Object – depends on
type of object
•
•
•
•
•
Short – sht
Integer – int
Long – lng
Single – sng
Double – dbl
© 2009
2
Declaration
• Variables and Named Constants must be
declared before being used in code
• When you declare a Variable or Named Constant
C#
– Reserves an area of memory
– Assigns it a name called an Identifier
• Declaration statements are coded either
– Beginning of a procedure
General Declarations of a module
3- 7
â 2009
Declaration Statements
ã CONST used to declare Named Constants
• Declaration includes
–
–
–
–
Name, follow Naming Convention Rules
Data Type
Required Value for Constants
Optional Initial Value for Variables
• Declare variable:
– Data_Type
– Data_Type
var_name;
var_name = init_value;
• Declare const
– Data_Type
const
const_name = value;
3- 8
© 2009
Declaration Examples
string strName, strSSN ;
int intAge;
decimal decPayRate ;
decimal decTax=0.1 ;
bool blnInsured
;
long lngPopulation ;
decimal decDT, decCD, decCR;
decimal decHour, decSumSal, decDiemTB, decSum=0;
decimal decTAX = 0.12, decHSLUONG=3.16;
Const decimal decDISCOUNT_RATE = 0.15M;
Note: Constants are named using all
uppercase letters EXCEPT the prefix.
3- 9
© 2009
3
Variables – Scope & Lifetime
• Global/Public (use sparingly and cautiously)
– Available to all modules and procedures of Project
– Initialized at start of Project
• Module/Private
(Form)
– Available to one module and all procedures within that module
– Initialized 1st time the Form is loaded
• Local
– Available only to the procedure it is declared in
– Initialized every time the Procedure runs
• Block (not used until later in this course)
– Available only to the block of code inside a procedure it is declared in
– Initialized every time the Procedure runs
3- 10
â 2009
Naming Rules (*)
ã You must follow when creating variable and constant
names
– Names can include letters, digits, and the underscore, but must
begin with a letter
– Names cannot contain spaces or periods
– Names cannot be # reserved words such as new, class, public, or
conts (keyworks)
– Names are not case sensitive
– For all intensive purposes, a Name can be as long as you want (the
actual limit is 16,383 characters in length).
3- 11
© 2009
Accessibility Domains
Keyword
Public
Private
Protected
3- 12
Description
Accessible from anywhere in the program
or from any other program
that references this one.
Accessible from anywhere inside this class.
Accessible from anywhere inside this class
or in any class that inherits from this class.
© 2009
4
Scope (Phạm vi biến)
•
Public
•
Module/Private
– Available to all modules and procedures of Project
– Must be referenced by the namespace
(Form)
– Can be used in any procedure on a specific Form, but is not visible to
other Forms
– Initialized 1st time the Form is loaded
•
Local
•
Block
– Available only to the procedure it is declared in
– Initialized every time the Procedure runs
– Available only to the block of code inside a procedure it is declared in
– Initialized every time the Procedure runs
3- 13
© 2009
Scope Declaring & Naming
• Global/Public
g prefix
– Declare in General Declarations as Public
string gstrName;
• Module/Private
m prefix
– Declare in Module’s General Declarations as Private
const decimal mdecSUADA = 2.5D;
decimal mdecSubToTal1KH, decToTalDue1KHCoThue;
int mintTongSoKH;
• Local
no prefix required
– Declare in Event Procedures
string strName
3- 14
© 2009
Declaring Local Level
Variables Example
Local Level Variables
3- 15
© 2009
5
Declaring Module Level Variables Example
Module - Level
Variables and Constants
3- 16
© 2009
Declaring Block Level Variables Example
int a,b;
Block Level Variables
if (a > b)
{
int max;
max = a;
}
Block Level Variables
else
{
int max;
max = b;
}
3- 17
© 2009
Calculations
• Calculations can be performed using
properties of certain objects, variables,
constants, and numeric literals
• Do Not use Strings in calculations
• Values from Text property of Text Boxes
– Are Strings, even if they contain numeric data
– Must be converted to a Numeric Data Type
3- 18
© 2009
6
Conversion Examples
intQuantity
decPrice
intWholeNumber
decDollars
strValue
=
=
=
=
=
Convert.ToInt32 (txtQuantity.Text)
Convert.ToDecimal (txtPrice.Text)
Convert.ToInt32(decFractionalValue)
Convert.ToDecimal(intDollars)
Convert.ToString (decValue)
Function
Name
Argument
To Be Acted Upon
3- 19
© 2009
Mathematical Operators
Operator
Operation
Addition
+
-
Subtraction
*
Multiplication
/
Division
%
Modulus (division's
remainder)
3- 20
â 2009
Mathematical Order of
Operations
ã Computers solve math formulas based on a
specific order 1st, then left to right
1.
2.
3.
4.
5.
3- 21
Parentheses
Exponentiation
Multiplication & Division
Modulus
Addition & Subtraction
© 2009
7
Mathematical Examples
• Note the use of parentheses to control
3+4*2 = 11 Multiply then add
(3+4)*2 = 14 Parentheses control: add then multiply
8/4*2 = 4
Same level, left to right: divide then multiply
3- 22
© 2009
Mathematical Examples
Thứ tự thực hiện
3- 23
© 2009
Mathematical Examples
Thứ tự thưc hiện
3- 24
© 2009
8
Handling Exceptions
• Exceptions occur when user enters
unexpected/invalid data and program code
does not anticipate this possibility, such as
– User enters nonnumeric data in Text Box and
code attempts to run a Numeric Conversion
Function
– User enters data that results in division by zero
3- 25
â 2009
Try/Catch Blocks
ã Used to catch and handle exceptions;
referred to as error trapping or handling
• Enclose statements that might cause an
error within Try/Catch Block
– If an error occurs control is transferred to the
Catch Block
3- 26
© 2009
Try Block - General Form
Try
{
statements that may cause error
}
catch [ExceptionType VariableName ]
{
statements for action when an exception occurs
}
3- 27
© 2009
9
Try Block - Example 1
Catches All Exceptions
try
{
intQuantity=CInt(txtQuantity.Text)
lblQuantity.Text=CStr(intQuantity)
}
catch
{
lblMessage.Text="Error in input data.“
// thơng thường báo qua MessageBox.Show (???)
}
3- 28
© 2009
Try Block - Example 2
Catches Specific Exception
try
{
intQuantity=CInt(txtQuantity.Text)
lblQuantity.Text=CStr(intQuantity)
}
catch (InvalidCastException MyErr )
{
lblMessage.Text="Error in input data."
}
catch (DivideByZeroException MyErr )
{
lblMessage.Text="Error chia cho không."
}
3- 29
Conversion exception, usually caused
by nonnumeric or blank data
© 2009
Try Block - Example 3
Catches Multiple Specific Exceptions
try
{
statements that may cause errors
}
catch (InvalidCastException MyErr )
{
error messages and statements for nonnumeric data
}
catch (ArithmeticException MyErr )
{
error messages and statements for calculation problems
}
catch (Exception MyErr )
{
error messages and statements for any other exception
}
3- 30
© 2009
10
MessageBox Object
• Use Show Method of MessageBox to
display special type of window
• Arguments of Show method
–
–
–
–
Message to display
Optional Title Bar Caption
Optional Button(s)
Optional Icon
3- 31
â 2009
MessageBox Syntax
ã The MessageBox is an Overloaded Method
– Overloading – ability to call different versions of a procedure
based on the number and data types of the arguments passed to that
procedure
– The number and data types of the arguments expected by a
procedure are called Signatures
– There are multiple Signatures to choose from
– Arguments must be included to exactly match one of the
predefined Signatures
MessageBox.Show (TextMessage, TitlebarText, _
MessageBoxButtons, MesssageBoxIcon)
3- 32
â 2009
MessageBoxButtons
Constants
ã
ã
ã
ã
ã
ã
3- 33
OK
OKCancel
RetryCancel
YesNo
YesNoCancel
AbortRetryIgnore
â 2009
11
MessageBoxIcon Constants
ã
ã
ã
ã
ã
Asterisk
Error
Exclamation
Hand
Information
ã
ã
ã
ã
None
Question
Stop
Warning
3- 34
â 2009
Counting & Accumulating Sums
ã Must use Module/Form level variables since
Local/Event level variables reset to 0 each time
the procedure is called
• Summing
– mdecOrderTotal = mdecOrderTotal + decItemPrice
• Counting
– mintNumItems = mintNumItems + 1
– mintNumItems += mintNumItems
• Averaging
– mdecAveSale = mdecOrderTotal / mintNumItems
3- 35
© 2009
Ví Dụ Dùng Biến Cục Bộ
private void btnCong_Click(object sender, EventArgs e)
{ int intSoA, intSoB;
Double dblKetQua;
intSoA = int.Parse(txtA.Text);
intSoB = Convert.ToInt32(txtB.Text);
dblKetQua = intSoA + intSoB;
lblKQ.Text = dblKetQua.ToString();
}
3- 36
© 2009
12