Cis162ad c
This presentation is the property of its rightful owner.
Sponsored Links
1 / 49

CIS162AD – C# PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

CIS162AD – C#. Variables and Calculations 02_variables .ppt. Overview of Topics. Operating System and Memory Allocation Declaring Variables Data Types Text Boxes - for input and output Arithmetic Operators Designing User-Friendly Interfaces. Computer Resources.

Download Presentation

CIS162AD – C#

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

Cis162ad c

CIS162AD – C#

Variables and Calculations


Overview of topics

Overview of Topics

  • Operating System and Memory Allocation

  • Declaring Variables

  • Data Types

  • Text Boxes - for input and output

  • Arithmetic Operators

  • Designing User-Friendly Interfaces

Computer resources

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…

Software two major categories

Software: Two Major Categories

  • Operating System (OS)

  • Application Software

Operating system os

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.

Main memory

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.

Memory location

Memory Location

Address 1

Address 2

Address 3

Address 4

Address 5


All consecutive

Trivia question

Trivia Question

  • What is a nibble?

  • A nibble is half a byte.

  • A byte is 8 bits, so a nibble is 4 bits. 

Application software

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…

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.

CS2 – Dept Contact

Variable declaration

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.

Variable initialization

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.

Assigning values to variables

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;

When to declare variables

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.

Variables allocated memory

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.

Memory allocation

Memory Allocation


Variables in memory

Variables in Memory

Memory analogy

Memory Analogy

Naming rules

Naming Rules

  • Must begin with a letter.

    intHours intQtydecPrice

  • Rest can be letters, digits, or underscores.


  • C# is case sensitive.

    inthours intHoursintHOURS

    Each of these would reference a different memory location.

  • Keywords or reserved words cannot be used.

Preferred naming conventions

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;

Tribune 12 30 1999

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.

Tribune 12 30 1999 continued

Tribune, 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.

Other significant changes

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.

Use good variable names

Use Good Variable Names

Variable scope

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 { }.

Global vs local

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;

Lifetime of global variables

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).

Class level variables

Class-Level Variables

namespace 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}



Lifetime of local variables

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.

Sub procedure variables

Sub Procedure Variables

namespace 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}



Global variable misuse

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.

Data types

Data Types

  • Integer

  • Floating Point

  • Alphanumeric

  • Boolean

  • Date

Integers whole numbers or

Integers – whole numbers (+ or -)

Floating point decimal values

Floating Point – decimal values

Alphanumeric boolean and date

Alphanumeric, Boolean, and Date

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.



  • 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//InputtxtName.Text = strName//Output

Labels as prompts

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:

Converting with parse method

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 intQty;decimal decPrice;decimal decSubtotal;intQty = int.Parse(quantityTextBox.Text);decPrice = decimal.Parse(priceTextBox.Text);decSubtotal = intQty * decPrice;

Tostring function

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

Format specifier codes for tostring

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

Arithmetic operations

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.

Order of precedence

Order 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

Shortcut operators

Shortcut 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;

Increment and decrement operators

Increment and Decrement Operators

  • ++ adds one to a variable:

    cintSaleCount = cintSaleCount + 1;

    cintSaleCount += 1;


  • -- subtracts one to a variable:

    cintSaleCount = cintSaleCount - 1;

    cintSaleCount -= 1;


Program remarks

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*/

Designing user friendly interfaces

Designing 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)



  • Operating System and Memory Allocation

  • Declaring Variables

  • Data Types

  • Input/Output

  • Arithmetic Operations

  • Designing User-Friendly Interfaces

Designing user friendly interfaces1

Designing User-Friendly Interfaces

  • Text Property: E&xit 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.

  • Login