Title: CIS162AD C
1CIS162AD C
- Variables and Calculations
- 02_variables.ppt
2Overview of Topics
- Operating System and Memory Allocation
- Declaring Variables
- Data Types
- Text Boxes - for input and output
- Arithmetic Operators
- Designing User-Friendly Interfaces
3Computer Resources
- As we go through the course, we will want to
conceptually understand - Memory allocation
- Storage
- Well cover storage later, butlets look at
memory now
4Software Two Major Categories
- Operating System (OS)
- Application Software
5Operating 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 ExamplesWindows, UNIX, DOS, VMS, etc.
6Main 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.
7Memory Location
Address 1 Address 2 Address 3 Address 4 Address
5 Etc All consecutive
8Trivia Question
- What is a nibble?
- A nibble is half a byte.
- A byte is 8 bits, so a nibble is 4 bits. ?
9Application 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
10CS2 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.
11Variable Declaration
- Variables are declared by specifying the data
type and name of the variable. - Syntax dataType variableNameint
intQtydecimal decPrice string strName - The dataType specifies that only numbers or
strings can be assigned to the named variable.
12Variable 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.
13Assigning 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
14When 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.
15Variables Allocated Memory
- Within CS3s 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.
16Memory Allocation
Applications
17Variables in Memory
18Memory Analogy
19Naming 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.
20Preferred 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
21Tribune, 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.
22Tribune, 12/30/1999 continued
- Data 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.
23Other Significant Changes
- Area code in Phoenix required (2000).
- Year Two Thousand Y2K (1999).
- Zip4
- 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.
24Use Good Variable Names
25Variable 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 .
26Global 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
27Lifetime 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).
28Class-Level Variables
- namespace CS3
- public class CS3Form int cintQuantitySum in
t 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 -
29Lifetime 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.
30Sub Procedure Variables
- namespace CS3
- public class CS3Form int cintQuantitySum in
t 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 -
-
31Global 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.
32Data Types
- Integer
- Floating Point
- Alphanumeric
- Boolean
- Date
33Integers whole numbers ( or -)
34Floating Point decimal values
35Alphanumeric, Boolean, and Date
36Input/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.
37TextBoxes
- 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 txtN
ame.Text strName //Output
38Labels 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
39Converting 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
40ToString 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
41Format 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
42Arithmetic 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.
43Order of Precedence
- Inner to outer parentheses
- Left to right
- Multiplication and Division
- Modulus
- Addition and Subtraction
- Which is correct for 5 discount
- decDiscountAmt decQty (decPrice decPrice
.05) - decDiscountAmt decQty decPrice decPrice
.05
44Shortcut Operators
- The following assignment operators are shortcuts
for the standard longer forms of some
expressions. - , -, , /,
- Accumulation
- cdecQtySum cdecQtySum decQty
- cdecQtySum decQty
- Count
- cintSaleCount cintSaleCount 1
- cintSaleCount 1
45Increment 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--
46Program 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/
47Designing User-Friendly Interfaces
- How are access keys defined?
- How is the Default button Property set? (Enter
Key) - How is the Cancel button Property set? (ESC Key)
- What is meant by a control object having focus?
- What is Tab Stop and Tab Index properties used
for? - What are Tool Tips used for?
- Can focus and control properties (forecolor,
text) be changed at runtime using C Code?(See
last slide for answers)
48Summary
- Operating System and Memory Allocation
- Declaring Variables
- Data Types
- Input/Output
- Arithmetic Operations
- Designing User-Friendly Interfaces
49Designing User-Friendly Interfaces
- Text Property Exit for Exit and use Alt-x
- Set AcceptButton property on the form to a button
name. - Set CancelButton property on the form to a button
name. - It is the object that the user is currently on
and can type into it or press enter to select it. - 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. - Provides hints to the user when they mouse over a
control. - Yes.