1 / 49

CIS162AD – C#

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.

tyson
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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CIS162AD – C# Variables and Calculations 02_variables.ppt

  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

  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…

  4. Software: Two Major Categories • Operating System (OS) • Application Software

  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.

  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.

  7. Memory Location Address 1 Address 2 Address 3 Address 4 Address 5 Etc All consecutive

  8. Trivia Question • What is a nibble? • A nibble is half a byte. • A byte is 8 bits, so a nibble is 4 bits. 

  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…

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

  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.

  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.

  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;

  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.

  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.

  16. Memory Allocation Applications

  17. Variables in Memory

  18. Memory Analogy

  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.

  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;

  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.

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

  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.

  24. Use Good Variable Names

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

  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;

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

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

  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.

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

  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.

  32. Data Types • Integer • Floating Point • Alphanumeric • Boolean • Date

  33. Integers – whole numbers (+ or -)

  34. Floating Point – decimal values

  35. Alphanumeric, Boolean, and Date

  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.

  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

  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:

  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;

  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

  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

  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.

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

  44. 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;

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

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

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

  48. Summary • Operating System and Memory Allocation • Declaring Variables • Data Types • Input/Output • Arithmetic Operations • Designing User-Friendly Interfaces

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

More Related