0% found this document useful (0 votes)
38 views47 pages

4.01 Understand Variables Final

The document discusses variables and naming conventions in computer programming. It defines what a variable is and different data types that variables can have. It also covers declaring variables, assigning values, and getting input from users using text boxes.

Uploaded by

acthor201
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views47 pages

4.01 Understand Variables Final

The document discusses variables and naming conventions in computer programming. It defines what a variable is and different data types that variables can have. It also covers declaring variables, assigning values, and getting input from users using text boxes.

Uploaded by

acthor201
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

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%)
3

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.


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

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 05/22/2024


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.
Examples:
10
 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

Computer Programming I- Summer 2011 05/22/2024


Data Types

Data Type Storage Value Range

Integer 4 Bytes -2,147,483,648 to 2,147,483,647

Double 8 Bytes 1.7E +/- 308 (15 digits)

Decimal 16 Bytes 1.7E +/- 308 (15 digits)

Char 1 Byte –128 to 127 by default

Boolean 1 Byte True or False

String Varies 0 to approximately 2 billion Unicode


characters
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.
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.
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).
Initialize Variable
15

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 05/22/2024


Assignment Statement

Dim intSide As Integer = 10


Keyword to Value that
Declare a matches
Variable DataType

Variable Assignment
Name =

Keyword
before the DataType
Data Type
Assignment Statement

Dim intSide As Integer = 10

intSide
Creates the
place in 10
memory

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.

1. Global
 Can be called anywhere in the program

2. Local
 Can only be called in the sub/function it is declared in

3. Procedural
 Can only be used in the block of code it is declared it
 Example: within an IF statement or loop
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


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

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
Using a TextChanged Event
33

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 05/22/2024


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

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
46

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 05/22/2024


Vocabulary

Object
Naming Conventions for our objects

You might also like