cis162ad – c# variables and calculations 02_variables.ppt
TRANSCRIPT
CIS162AD – C#
Variables and Calculations02_variables.ppt
CIS162AD 2
Overview of Topics
Operating System and Memory Allocation Declaring Variables Data Types Text Boxes - for input and output Arithmetic Operators Designing User-Friendly Interfaces
CIS162AD 3
Computer Resources
As we go through the course, we will want to conceptually understand – Memory allocation– Storage
We’ll cover storage later, butlet’s look at memory now…
CIS162AD 4
Software: Two Major Categories
Operating System (OS) Application Software
CIS162AD 5
Operating System (OS)
Software that allocates and monitors computer resources including memory allocation, storage, and security.
Various devices are controlled using system programs called drivers.
OS Examples:Windows, UNIX, DOS, VMS, etc.
CIS162AD 6
Main Memory Random Access Memory (RAM). Contents are lost when power is turned off. Measured in bytes. Each byte stores eight bits.
– BIT – Binary Digit (0 & 1) Each byte is considered a location. Each byte has an address to identify its location. Application currently running and the data being
manipulated must be loaded in memory (RAM). CPU only gets and stores data in RAM.
CIS162AD 7
Memory Location
Address 1
Address 2
Address 3
Address 4
Address 5
Etc
All consecutive
Byte 1
Byte 2
Byte 3
Byte 4
Byte 5
Etc
32, 64, 128, 256MB
CIS162AD 8
Trivia Question
What is a nibble? A nibble is half a byte. A byte is 8 bits, so a nibble is 4 bits.
CIS162AD 9
Application Software
Actual software we use to process raw data into information.
Word, Excel, Powerpoint, Access, etc. Application software is used in many industries.
– Business: Accounting, Sales– Manufacturing: Inventory, Labor– Education: Enrollment, Research– Personal: Budgeting, School– Too many applications to list…
CIS162AD 10
CS2 – Dept Contact CS2 is a program that displays the contacts for
various departments. The contact information is hard-coded in the
program. (phoneLabel.Text = “555-3434”) To create a more flexible and dynamic program we
can use variables. Variables are assigned storage locations in memory. The values in these memory locations can vary
during the execution of the program. Hard-coded values can not vary. Beginning with CS3 we will be using variables.
CIS162AD 11
Variable Declaration Variables are declared by specifying the data type and
name of the variable. Syntax:
dataType variableName;
int intQty;decimal decPrice;string strName;
The dataType specifies that only numbers or strings can be assigned to the named variable.
CIS162AD 12
Variable Initialization When a variable is declared they are assigned a default
value. String variables are set to null or nothing. Numeric variables are set to zero, but the compiler will
require that they be initialized before using them in a calculation or trying to display them.
Treat local numeric variables as if they have not been initialized.
Variables can be initialized to a value when declared or by assigning a value to them.
CIS162AD 13
Assigning Values to Variables
Assigning values at declaration is called initialization. To initialize use the equal sign followed by a value.
int hours; //not initialized
int hours = 0; //initialized to zero
Assignment statement is the use of the equal sign:
decPrice = decimal.Parse (priceTextBox.Text);
decGross = intHours * decRate;
CIS162AD 14
When to Declare Variables
Variables can technically be declared anytime before they are used.
However, in structured programming, we define our variables at the beginning of a program or method.
CIS162AD 15
Variables Allocated Memory
Within CS3’s memory allocation, variables are assigned a memory location.
Each time the program is ran, a different address may be assigned.
The computer uses the memory address, but we programmers reference that location with the variable name.
CIS162AD 16
Memory Allocation
Operating System (OS)
Display.drv
KeyBd.drv
Mouse.drv
CS3
Applications
CIS162AD 17
Variables in Memory
Variable Name Address (hex) Value
intQty A000 0
decPrice A008 0
strName A016
CIS162AD 18
Memory Analogy
Variable Name Address (hex) Value
intQty A000 0
decPrice A008 0
strName A016
MCC 1833 W. Southern
CIS162AD 19
Naming Rules Must begin with a letter.
intHours intQty decPrice
Rest can be letters, digits, or underscores.intHours intHours1 intHours_1
C# is case sensitive.inthours intHours intHOURS
Each of these would reference a different memory location.
Keywords or reserved words cannot be used.
CIS162AD 20
Preferred Naming Conventions Variables should have meaningful names. Precede each variable name with a prefix of three
letters in lowercase to clarify the data type. Camel-case: all lowercase with the first letter of
significant words in upper case .intQty, decPrice, strName, intHoursWorked
Variables defined as constants (will not change value during the execution) should be in all uppercase with significant words separated with an underscore.
decTAX_RATE, decTUITION_RATE Use the const modifier for constants.
const decimal decTAX_RATE = 0.07M;
CIS162AD 21
Tribune, 12/30/1999
Programmers Double-check for Last-minute Y2K Bugs.
…Experts said early efforts focused on checking dates – typically identified with a heading “mm-dd-yy” or “date” – buried within computer code. But prankster programmers sometimes used unusual names that can make these data variables nearly impossible to find.
CIS162AD 22
Tribune, 12/30/1999 continuedData Integrity said it found a date variable called
“Shirley”… The programmer responsible, it turned out, was dating a woman named Shirley when he wrote the software.
Air Force experts compete in a “variable of the week” contest to find the most obscure title for a date field.
The name of a girlfriend, athlete, movie stars is unfortunately all too common as programmers express their creative free will.
CIS162AD 23
Other Significant Changes
Area code in Phoenix required (2000). Year Two Thousand – Y2K (1999). Zip+4 Income tax laws and tax rates. Sales tax rates different in each city. The point is that there will always be some
maintenance on programs, so make it easy to maintain.
CIS162AD 24
Use Good Variable Names
Variable Name Address (hex) Value
intQty A000 0
decPrice A008 0
strName A016
MCC 1833 W. Southern
Bad
q
p
s
M
CIS162AD 25
Variable Scope Variables can only be referenced within the section of
code it was declared in. Namespace variables may be referenced in entire
project (multi-form project). Class-level variables may be referenced in all methods
of a form. Local variables may be referenced only within the
method in which it was declared. Block variables may be referenced only within a block
of code inside a method. if and do statements create a block of code as well as
the open and close braces { }.
CIS162AD 26
Global vs Local
These terms are used to group the type of variables that can be created.
Global refers to the Class-level and Namespace variables.
Local refers to the Method and Block variables When using class-level variables, an additional
prefix is added to the name (c).decimal cdecTotalPay;
CIS162AD 27
Lifetime of Global Variables
Class-level and Namespace variables exist for the entire time a form is loaded.
Use global variables to store constants. Use global variables to store a running total
(accumulation) or count that is displayed at the end of a session (ie: number of transactions posted, total sales).
CIS162AD 28
Class-Level Variablesnamespace CS3{
public class CS3Form{
int cintQuantitySum;int cintSaleCount;const decimal cdecDISCOUNT_RATE = 0.15M;
private void calculateButton_Click(…){
… class-level variables can be referenced here}
private void summaryButton_Click(…){
… class-level variables can be referenced here}
}}
CIS162AD 29
Lifetime of Local Variables
The lifetime of a variable is the period of time that the variables exists.
Method and Block variables exist for one execution of the method.
Each time a method is executed, the local variables are created again and initialized to its default value.
When the method is exited, its variables are destroyed, and their memory locations are released.
Any values that were stored in the local variables are gone.
CIS162AD 30
Sub Procedure Variablesnamespace CS3{
public class CS3Form{
int cintQuantitySum;int cintSaleCount;const decimal cdecDISCOUNT_RATE = 0.15M;
private void calculateButton_Click(…){
int intQuanity;decimal decPrice;
}
private void summaryButton_Click(…){
decimal decExtended;
decExtended = intQuantity * decPrice;
//Error - intQuantity and decPrice not defined in procedure }}
}
CIS162AD 31
Global Variable Misuse Do NOT use global variables to store values that
change and could be declared as local variables in methods. Even if a variable of the same name and type is needed in various procedures.
Using global variables to store local values– leads to bad programming habits– makes the code in methods less reusable in other programs
(same variable names would need to be used in all programs).
Later we will be defining our own methods, and we will understand better why Global variables are not necessarily good.
CIS162AD 32
Data Types
Integer Floating Point Alphanumeric Boolean Date
CIS162AD 33
Integers – whole numbers (+ or -)
byte 1 byte 0-255 ±
short 2 bytes 32,767 ±
int 4 bytes Just over 2.1 billion ±
long 8 bytes Very large number
CIS162AD 34
Floating Point – decimal values
float 4 bytes “single precision” – 6 digits to the right of the decimal point.
double 8 bytes”double precision” – 14 digits to right of the decimal point.
decimal 16 bytes28 digits to right of the decimal point
CIS162AD 35
Alphanumeric, Boolean, and Date
char 2 Bytes1 Unicode character(ASCII 8 bits Unicode 16 bits)
string varies 1 or more characters
bool 1 byte Boolean: True or False
DateTime 8 Bytes01/01/0001 - 12/31/9999 includes HH:MM:SS
CIS162AD 36
Input/Output
We need a user interface to get their Input and to display processing results as Output.
We use variables to store the values entered by the user and to store the results of the processing.
In C#, textboxes are the most common control object used to facilitate I/O.
CIS162AD 37
TextBoxes Contents of a textbox is always a String. Can get and assigned values to a textbox. Use the property Text.
string strName;
strName = txtName.Text //Input
txtName.Text = strName //Output
CIS162AD 38
Labels as Prompts
It is important to display a prompt to the user so they know what input is expected.
A prompt is a brief description or label for the data to be entered.
The user interface must be friendly. Use control object Label.
Name: Address:
CIS162AD 39
Converting with Parse Method Numbers are also stored as Strings in textboxes. The String must be converted to a number before being
assigned to a numeric variable, and before being used in a arithmetic expression.
Each datatype has a Parse method for conversion.int intQty;decimal decPrice;decimal decSubtotal;
intQty = int.Parse(quantityTextBox.Text);decPrice = decimal.Parse(priceTextBox.Text);
decSubtotal = intQty * decPrice;
CIS162AD 40
ToString Function To display a number in a textbox it is must be
converted from a number to a String. Use built-in function ToString.
decSubtotal = intQty * decPrice;
subtotalTextBox.Text = decSubtotal.ToString(“N”);
N is a Format Specifier Code – see next slide
CIS162AD 41
Format Specifier Codes for ToString
Use the codes to format the display of output. N stands for Number
– Adds comma and includes 2 digits to the right of the decimal point.
C stands for Currency– Adds dollar sign, comma and includes 2 digits to the right
of the decimal point
Specify a specify number of decimal positions by including a number in the string: “C0”, “N4”– The value is rounded to the specified number
CIS162AD 42
Arithmetic Operations
Arithmetic operations are the mathematical operations we can perform in our programs.
Add (+) and Subtract (-) Multiply (*) and Divide (/) Modulus (%), returns the remainder of a division
operation (intMin = intTotal % 60) Exponentiation – use Pow method of Math class. Use parentheses to specify which operations should
occur first.
CIS162AD 43
Order of Precedence1. Inner to outer parentheses2. Left to right3. Multiplication and Division4. Modulus5. Addition and Subtraction
Which is correct for 5% discount:
decDiscountAmt = decQty * (decPrice – decPrice * .05) decDiscountAmt = decQty * decPrice – decPrice * .05
CIS162AD 44
Shortcut Operators
The following assignment operators are shortcuts for the standard longer forms of some expressions.+=, -=, *=, /=, %=
AccumulationcdecQtySum = cdecQtySum + decQty;
cdecQtySum += decQty;
CountcintSaleCount = cintSaleCount + 1;
cintSaleCount += 1;
CIS162AD 45
Increment and Decrement Operators
++ adds one to a variable:cintSaleCount = cintSaleCount + 1;
cintSaleCount += 1;
cintSaleCount++;
-- subtracts one to a variable:cintSaleCount = cintSaleCount - 1;
cintSaleCount -= 1;
cintSaleCount--;
CIS162AD 46
Program Remarks Comments should be included in each program
(see Grading Criteria handout). Comments are ignored by the compiler. Comments are for you and other programmers that will
eventually need to come back to maintain the program. Use two slashes (//) for single line remark.
//This is a single line comment
Use the open (/*) and close (*/) remark for a multi-line remark.
/* This is a multi-line comment used for longer comments*/
CIS162AD 47
Designing User-Friendly Interfaces
1. How are access keys defined?2. How is the Default button Property set? (Enter Key)
3. How is the Cancel button Property set? (ESC Key)
4. What is meant by a control object having focus?5. What is Tab Stop and Tab Index properties used for?6. What are Tool Tips used for?7. Can focus and control properties (forecolor, text) be
changed at runtime using C# Code?
(See last slide for answers)
CIS162AD 48
Summary
Operating System and Memory Allocation Declaring Variables Data Types Input/Output Arithmetic Operations Designing User-Friendly Interfaces
CIS162AD 49
Designing User-Friendly Interfaces
1. Text Property: E&xit for Exit and use Alt-x2. Set AcceptButton property on the form to a button name.3. Set CancelButton property on the form to a button name.4. It is the object that the user is currently on and can type
into it or press enter to select it.5. TabStop determines if a user can tab to the control, and
TabIndex determines the order the user will move from control to control when the tab key is pressed.
6. Provides hints to the user when they mouse over a control.7. Yes.