Understand Variables and Naming Conventions

Slides:



Advertisements
Similar presentations
5.04 Apply Decision Making Structures
Advertisements

Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
5.05 Apply Looping Structures
COMPUTER PROGRAMMING II SUMMER 2011 Visual Basic to C#
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
Apply Sub Procedures/Methods and User Defined Functions
Variables and Constants
Chapter 3: Using Variables and Constants
CS0004: Introduction to Programming Variables – Numbers.
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
Lecture 8 Visual Basic (2).
3 - Variables Lingma Acheson Department of Computer and Information Science, IUPUI CSCI N331 VB.NET Programming.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Working with the VB IDE. Running a Program u Clicking the”start” tool begins the program u The “break” tool pauses a program in mid-execution u The “end”
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
COMPUTER PROGRAMMING II SUMMER 2011 Visual Basic to C#
Data Types and Variables. Data Type! Computers are all about Data! Data can be in the form of Text Dates Sounds Pictures.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
# 1# 1 What is a variable that you create? What is a constant that you create? What is an intrinsic (built-in) constant? What variables are built in?
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
Programming with Microsoft Visual Basic th Edition
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
Variables Hold information that may be manipulated, used to manipulate other information or remembered for later use A storage location in memory (RAM)
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 3 Variables and Calculations.
Making Interactive Programs with Visual Basic .NET
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
Welcome to Computer Programming II! Computer Programming II Summer 2015.
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
Bill Tucker Austin Community College COSC 1315
Use TryParse to Validate User Input
Visual Basic.NET Windows Programming
Egyptian Language School Computer Department
5.04 Apply Decision Making Structures
A variable is a name for a value stored in memory.
Chapter 2 Variables.
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Chapter 2 Basic Computation
An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use.
Variables and Arithmetic Operations
Chapter 3: Using Variables and Constants
Computer Programming I
Single Dimensional Arrays
Use TryParse to Validate User Input
2. Understanding VB Variables
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Lecture Set 4 Data Types and Variables
Variables and Arithmetic Operations
Microsoft Visual Basic 2005 BASICS
Visual Basic Programming Chapter Four Notes Working with Variables, Constants, Data Types, and Expressions GROUPBOX CONTROL The _____________________________________.
CIS16 Application Development Programming with Visual Basic
Chapter 2 Variables.
C++ Data Types Data Type
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
CHAPTER FOUR VARIABLES AND CONSTANTS
Chapter 2: Introduction to C++.
Chapter 2 Variables.
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Variables and Constants
Presentation transcript:

Understand Variables and Naming Conventions Computer Programming I

Objective/Essential Standard Essential Standard: 4.00 Understand Variables and Naming Conventions Indicator 4.01Understand Variables and Data Types (5%) Indicator 4.02 Understand Object Naming (3%)

Indicator 4.01 Understand Variables and Data Types (5%) Computer programming 1

Variable Hey what do you know? Something you learned in Algebra I will be used in another class?! What is a variable?

Variables Hey what do you know? Something you learned in Algebra I will be used in another class?! What is a variable? Simply put- a variable is a named place in computer memory that holds a value. The user (who runs the program) or the programmer (coder) can supply the value of a variable. A variable can only hold one value at any given time. For example: i, j, intGrade, strName are variables. Naming conventions for variables are covered in this PowerPoint- objects are covered in Indicator 5.02.

Declare (Create) a Variable Using DIM Variables must be given (assigned) a name and data type. Syntax Dim varName As DataType Example Dim intNumber as Integer Dim (or another keyword- described later) is required in VB to declare a variable, in C# the data type goes first and tells C# that a variable is being declared. Notice that Integer is spelled out in VB but not in C#. Using “Integer” in C# will produce a syntax error.

Variable Basics To use a variable we first must “declare” it using the DIM keyword. This tells the computer the name we are going to use and its data type. A variable name is the address used when working with a variable (placing data inside, or changing the data). Like the address on your mailbox. A data type tells the computer what type of value to expect in a variable. Using the wrong data type can produce errors. For example trying to put “apple” in a variable of an integer data type will cause problems.

Keywords Visual Basic has reserved KEYWORDS that have special meaning. They appear in a different color When naming your variables, no keywords may be used. If you follow Hungarian notation properly, the prefix will keep this from happening! Computer Programming I- Summer 2011 9/22/2018

Data Types and Prefixes used in Names Common Data Types: Integer (int) used with whole numbers (+/-) String (str) used with strings of characters/words Double (dbl) used with larger decimal numbers Decimal (dec) used with decimal numbers - currency Char (chr) used for a single character Boolean (bln) used for true or false The prefixes for Hungarian notation are listed in the (). Use the prefixes to properly name variables. The prefixes in () are for Hungarian notation.

Examples: Integer (int) used with whole numbers (+/-) Dim intNumber As Integer String (str) used with strings of characters/words Dim strName As String Double (dbl) used with larger decimal numbers Dim dblRealNumber As Double Decimal (dec) used with decimal numbers – currency Dim decMoney As Decimal Char (chr) used for a single character Dim chrLetter As Char Boolean (bln) used for true or false Dim blnQuestion As Boolean Create the variable names with a prefix that shows which data type is used. Use a full English word with a Capital. Ex intCounter Use Decimal for all currency Float not used in this course, used for small numbers – will be used in Programming II Computer Programming I- Summer 2011 9/22/2018

Data Types Data Type Storage Value Range Integer 4 Bytes Double 8 Bytes 1.7E +/- 308 (15 digits) Decimal 16 Bytes Char 1 Byte –128 to 127 by default Boolean True or False String Varies 0 to approximately 2 billion Unicode characters String and Char hold text and numbers. All the other data types listed are for numbers except Boolean which is a binary variable- TRUE or FALSE are the two possible values.

Variable Naming Rules Variables should have a descriptive name that describes their purpose and data type. Examples: intGrade, strName, decTaxRate, dblTotalSales Do not capitalize the prefix but do capitalize the first letter of each subsequent word. strLastName intStdNum Variable names cannot start with numbers or have spaces or special characters except for the underscore. This is called Hungarian notation and is common in Windows programming.

Initial Values when Declaring a Variable Example: Dim intNumber as Integer When a numeric variable is declared, its initial value is 0 unless it is given a value at the same time. When a string variables is declared without a value, its initial value is null. The compiler will not like this. Dim (or another keyword- described later) is required in VB to declare a variable, in C# the data type goes first and tells C# that a variable is being declared. Notice that Integer is spelled out in VB but not in C#. Using “Integer” in C# will produce a syntax error.

Initialize Variables After we declare a variable we must give it a value. This is called assignment and is done with the assignment operator (=) This can be done several ways: Dim intNumber as Integer = 0 Dim intNumber as Integer intNumber = 0 Variables can be assigned values like numbers or strings or be assigned values from other sources (like a textbox). In VB the assignment operator is also used for comparisons of equality. This is NOT the case in C#.

Initialize Variable Always initialize your variables, even if it is to 0 or Nothing. Numeric variables of all types can be initialized to zero. Dim intNum As Integer = 0 String variables can be set to “empty” two ways: Dim strName As String = “” Dim strName As String = Nothing NOTHING is a keyword Computer Programming I- Summer 2011 9/22/2018

Assignment Statement Dim intSide As Integer = 10 Keyword to Declare a Variable Value that matches DataType Variable Name Assignment = DataType Keyword before the Data Type

Dim intSide As Integer = 10 Assignment Statement Dim intSide As Integer = 10 intSide Creates the place in memory 10 The actual value that will “reside” in the memory place. Also known as a literal.

Variable Rules Whenever a data type of string or char is used their values must be enclosed in quotes. For example: strName=“Alex” chrLetterGrade= “A” Do not enclose numbers in quotes when using a number data type (integer, float, double, etc.)

Variable Rules Only number data types can be used in calculations. Strings can be combined from several different sources. This is called concatenation. Use & in between each segment. strData = “This is some data “ & intNum & “and this is a number.”

Variable Scope Variables only exist within their defined scope. The time that the variable is available for use is called its lifetime. A variable cannot be called from outside that scope. There are 3 different types of scope. Global Can be called anywhere in the program Local Can only be called in the sub/function it is declared in Procedural Can only be used in the block of code it is declared in Example: within an IF statement or loop Global variables should be avoided unless absolutely required (there are cases when they are called for) as they are bad programming practice and open up the program to common attacks by hackers. C# does not support global variables.

Variable Scope A global variable is declared at the top of the program before any procedures or subs are called. Example public Class Form1 Dim intNumber As Integer . . . Global variables do not exist in C#. C# teachers ignore this slide.

Formatting Output Output is values or strings the program displays for the user based on the execution of the program. Frequently output needs to be formatted - that is displayed to the user in a readable format. There are functions that will allow you to format your output.

ToString One way to format output is use the ToString method. This converts any value given to it to a string and formats it with the format given. General format: label.Text = variable.ToString(“format”) For example: lblTotal.Text = decTotal.ToString("$##.00") General format: Variable/Label/Text Box = variable.ToString(“format”) The unpacked content has sample programs that contain output that should be formatted.

ToString Formats To find more formats http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#Y2728

Getting Input from the User Adding Textboxes to your projects

The TextBox Control To allow users to enter (input) values at run time, use the TextBox control. Click on the TextBox control in the Toolbox. Click on the Form. You can resize by dragging the handles. TextBox properties: (Name) – start with txt Text – what is displayed inside the text box Alignment – aligns the text relative to the text box. PasswordChar – Sets a character to be displayed in the textbox as the user types. For example, if the user types toy and the PasswordChar is set to *, *** is displayed in the textbox instead of “toy”

The TextBox Control

Using the TextBox Control To tell the user the purpose of the TextBox, add a Label control to the left of the TextBox. Type your prompt in the label Example Enter your last name: The label placed near the text box to describe its contents or purpose is called a prompt.

Using the TextBox Control Syntax to get a value from the TextBox strVariable = txtTextBox.Text Visual Basic Textbox example: strExample = Me.txtExample.Text The TextBox returns a string object.

Using the TextBox Control Because the TextBox returns a string, the programmer may want to convert the string to the another, appropriate datatype. Convert Method Convert is a function that changes the data type of a variable from one type to another. Common Convert Methods ToChar ToDouble ToInt32

Using the TextBox Control Examples of using the Convert method. intNum = Convert.ToInt32(strNumInput) intNum = Convert.ToInt32(txtNumInput.Text) dblGpa = Convert.ToDouble(strGpaInput) dblGpa = Convert.ToDouble(txtGpaInput.Text)

Input Does Not Match Variable DataType So what happens if you have the following code and the user enters “five”? dblSide = Convert.ToDouble(txtSide.Text) The Convert is going to try to convert the string entered into the TextBox into a numeric value for the variable. “five” cannot be converted to a numeric 5 Result: Error The application will stop running and revert to the code view with the above error.

Using a TextChanged Event TextChanged event procedure Executes when the user types in the text box. You can clear a label by creating a TextChanged event for your TextBoxes. Computer Programming I- Summer 2011 9/22/2018

Displaying Output Messagebox

Display Output In addition to labels and textboxes we can use message boxes to display output or alert users to fatal errors. MessageBox Syntax MessageBox.Show (“string here”) MessageBox.Show("Please enter numbers for sales and tax rate!") MessageBox.Show("Your name is: " & strName & " ." & “You are " & intAge & "years old.")

Sample Program Write a program that asks a user their name and age. Store this information in two variables and then using a message box show the information back to the user. Use a button to start the program. Next 2 slides contain the code to write the program. One slide contains the VB code the other the C# code.

VB Sample Code Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click Dim intAge as Integer = 0 ‘variable is initialized Dim strName as String = "“ ‘variable is initialized strName = txtName.Text ‘get input intAge = txtAge.Text ‘get input ‘Show output in MessageBox MessageBox.Show("Your name is: " & strName & " ." & “You are " & intAge & "years old.") End Sub

Advanced Variables Sometimes we need to use a variable in different ways. Like a variable that needs to hold its value beyond the end of the program or a variable whose value cannot be changed. When the variable is declared these options can be set. On the two slides that follow one is for VB and one is for C#.

Static/Constant Variables A static variable holds its value between runs of the program. This is used commonly with loops. Static variables cannot be defined globally. Static intNumber As Integer A constant variable is a variable that once declared cannot be changed by the program. Constant variables should be declared using all uppercase letters. Const decTAXRATE As Decimal = 0.775 Notice Dim is omitted and the keyword Static or Const is used instead to declare the variable. A constant variable must be given a value when it is declared or the program will produce an error. Once set this value cannot be changed elsewhere in the program.

Counter Variables A counter is a variable storing a number that is incremented by a constant value. Updating Counter Form: counter = counter + constant or counter += constant Initialize the counter when it is declared. It is then updated by an unchanging amount (the constant) A counter in an event procedure should be declared as a Static variable so that it is initialized once.

Vocabulary Variable Global Data Type Local Integer Procedural Double Output Decimal ToString Char TextBox Boolean Prompt String MessageBox Literal Static Variable Hungarian Notation Constant Variable Concatenation Counter Scope Assignment

Code Dim varName As DataType & label.Text = variable.ToString(“format”) strVariable = TextBox.Text MessageBox.Show (“string here”)

Indicator 4.02 - Understand Object Naming (4%) Computer Programming 1

Naming Objects In the last unit we learned about naming variables. Let’s focus on objects now. What is an object? Objects represent “real” things Dog, Chair… Label, Button Objects have properties and behaviors (methods) Button Properites: Name, Text … Behaviors/Methods: Click . . .

Naming Objects Common object names are listed below with examples in (): Form - frm (frmMain) Button - btn (btnSubmit) Label - lbl (lblTotal) Text Box - txt (txtAge) Radio Button- rad (radAdd) Check box - chk (chkDivide) Image - img (imgMegaMan) Combo Box - cbo (cboState) Picture Box - pic (picFlower) List box - lst (lstState) Menu - mnu (mnuFile)

Keyword “Me” used on Forms Ex: Me.Close Preceeding a form name with “Me” refers to the current form (The active one). Using Me is optional in VB 2010 in most cases when using only one form. When using multiple forms, opening and closing forms must use the Me.Hide or Me.Show. Computer Programming I- Summer 2011 9/22/2018

Vocabulary Object Naming Conventions for our objects