SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Variables and Calculations CBIS 112 Ms. Montanez
Gathering Text Input In this chapter, we use the TextBox control to gather input the user has typed on the keyboard, learn about the different types of variables types available in Visual Basic and how to use mathematical operators for calculations in a Windows form. At the end of the chapter, you will have completed the Digital Downloads project which entails the following tasks: Collect data from the user through a textbox field Define the Accept and Cancel properties within a form to accept user keyboard behavior to trigger events in a form Convert the text from the textbox field into a number that can use be used in calculations Define the variables needed to calculate the total cost of downloads for the user Debug application to ensure that it works properly
The TextBox Control A text box is a rectangular area on a form that accepts input from a keyboard The TextBox control’s Text property can be accessed in code the same way you access other properties
Enabling Multi-Line textboxes A Multi-line box will allow the user to enter multiple lines in a textbox.  You must resize the textbox vertically to display multiple lines.  By clicking on the Action tag, you can enable a textbox to accept multiple lines of text
Setting up Masks for fields entered in a textfield A masked textbox allows you to specify a particular format that must be used when entering data in a textbox.  Before the user enters data in a form, the masked textbox will display to the user the format of the data to be entered.
Keyboard responses in a text fields. Computer users often press the “Enter” key to enter data in a textbox to cause the processing to occur. On the same token, they might attempt to use the “Esc” key as a way to cancel or clear textbox results. To accept this type of user input, it is necessary to setup the Form properties “AcceptButton” and “CancelButton” to the corresponding buttons in a form. 
Why Have Variables? A variable is a storage location in the computer’s memory, used for holding information while the program is running The information that is stored in a variable may change, hence the name “variable”
What Can You Do With Variables? Copy and store values entered by the user, so they may be manipulated Perform arithmetic on values Test values to determine that they meet some criterion Temporarily hold and manipulate the value of a control property Remember information for later use in the program
How to Think About Variables You the programmer make up a name for the variable Visual Basic associates that name with a location in the computer's RAM The value currently associated with the variable is stored in that memory location
Declaring Variables A variable declaration is a statement that creates a variable in memory The syntax is: 	Dim VariableName As DataType Dim (short for Dimension) is a keyword VariableName is the programmer designated name As is a keyword DataType is one of many possible keywords for the type of value the variable will contain Here is an example of a variable declaration: 	Dim intLength as Integer
Declaring Multiple Variables Several variables may be declared in one statement if they all hold the same type of value Dim intLength, intWidth, intHeight as Integer Or this can be done in 3 separate statements Dim intLength as Integer Dim intWidth as Integer Dim intHeight as Integer
Variable Naming Rules The first character of a variable name must be a letter or an underscore Subsequent characters may be a letter, underscore, or digit Thus variable names cannot contain spaces or periods (or many other kinds of characters) Visual Basic keywords cannot be used as variable names
Variable Naming Conventions  Naming conventions are a guideline to help improve readability but not required syntax A variable name should describe its use Each data type has a recommended prefix, in lower case, that begins the variable name The 1st letter of each subsequent word in the variable name should be capitalized intHoursWorked - an integer variable strLastName - a string (or text) variable
Setting the Value of a Variable An assignment statement is used to set the value of a variable, as in: Assign the value 112 to the variable length length = 112 Assign the string literal “Good Morning “ followed by the contents of the text box txtName to the variable greeting greeting = "Good Morning " & txtName.Text An assignment changes only the left operand The right operand remains unchanged
Visual Basic Data Types Other data types Boolean Char String Date Integer types Byte Short Integer Long Floating-Point types Single Double Decimal
Integer Data Types For values that will always be a whole number Usually name a variable starting with a 3 or 4 letter prefix indicating the variable’s type
Floating-Point Data Types For values that may have fractional parts Single used most frequently Double sometimes used in scientific calculations Decimal often used in financial calculations
Other Common Data Types Boolean – variable naming prefix is bln Holds 2 possible values, True or False Char – variable naming prefix is chr Holds a single character Allows for characters from other languages String – variable naming prefix is str Holds a sequence of up to 2 billion characters Date – variable naming prefix is dat or dtm Can hold date and/or time information
The String Data Type A string literal is enclosed in quotation marks The following code assigns the name Jose Gonzales to the variable strName Dim strName as string strName = "Jose Gonzales" An empty string literal can be coded as: Two consecutive quotation marks  strName = "" Or by the special identifier String.Empty strName = String.Empty
The Date Data Type Date data type variables can hold the date and time or both You can assign a date literal to a Date variable, as shown here: Dim dtmBirth As Date dtmBirth = #5/1/2010# A date literal is enclosed within # symbols All of the following Date literals are valid:#12/10/2010# #8:45:00 PM# #10/20/2010 6:30:00 AM#
Assigning Text to a Variable Examples: Declare a string variable to hold thefull name. Dim strFullName As String ' Combine the first and last names' and copy the result to lblFullName strFullName = txtFirstName.Text & " " & txtLastName.Text lblFullName.Text = strFullName
Declaring Variables with IntelliSense As you enter your program, VB often aids you by offering a list of choices that could be used at that point After typing "As" in a variable declaration, VB will offer an alphabetical list of all possible data types Type the first few letters of the data type name IntelliSense box will highlight the matching type Press the Tab key to select highlighted choice Or just complete typing the entire data type name
Default Values and Initialization When a variable is first created in memory, it is assigned a default value numeric types are given a value of zero Boolean types are given a value of False strings are given a value of Nothing dates default to 12:00:00 AM January 1,1 Good practice to initialize string variables Dim strName as String = String.Empty String with value Nothing causes error if used
Initialization of Variables Can provide a starting or initialization value for any type of variable in a Dim statement Usually want to set an initial value unless assigning a value prior to using the variable Just append = value to the Dim statement where value is the literal to be assigned to the variable Dim intMonthsPerYear As Integer = 12
Scope and Local Variables  Scope refers to the part of the program where: A variable is visible and May be accessed by program code Variables declared within a procedure are called local variables and observe these characteristics Scope begins where variable is declared Extends to end of procedure where declared Variable is not visible outside the procedure  A variable cannot be declared twice in the same procedure
Performing Calculations Visual Basic has powerful arithmetic operators that perform calculations with numeric variables and literals. Variables used in arithmetic statements in a Visual Basic program must be numeric variables. String data entered by the user must be converted to numeric data before it can be used in an arithmetic statement. A procedure to convert a String data type into an Integer data type is named ToInt32
Common Arithmetic Operators Visual Basic provides operators for the common arithmetic operations: +	Addition -	Subtraction	 *	Multiplication /	Division ^	Exponentiation
Common Arithmetic Operators Addition dblTotal = dblPrice + dblTax Subtraction dblNetPrice = dblPrice – dblDiscount Multiplication intArea = intLength * intWidth Division dblAverage = intTotal / intItems Exponentiation dblCube = dblSide ^ 3
Arithmetic Operator Precedence Operator precedence tells us the order in which operations are performed  From highest to lowest precedence: Exponentiation (^) Multiplicative (* and /) Integer Division ( Modulus (MOD) Additive (+ and -) Where precedence is the same, operations occur from left to right
Grouping with Parentheses Parentheses () can be used to force selected parts of an expression to be evaluated before others Assume we’re computing the average of 3 numbers dblAvg = int1 + int2 + int3 / 3 	 ' incorrect int3 / 3 is evaluated first That result is added to int1 and int2 Use parentheses to control order of operations dblAvg = (int1 + int2 + int3) / 3	 ' correct int1 + int2 + int3 is evaulated first That result is divided by 3 When in doubt, use parentheses!
Converting Mathematical Expressions to Programming Statements In algebra, the mathematical expression 2xy describes the value 2 times x times y.  Visual Basic requires an operator for any mathematical operation.
Mixing Different Data Types When you assign a value of one data type to a variable of another data type, Visual Basic attempts to convert the value being assigned to the data type of the receiving variable.
Option Strict  Option Strict is a VB configuration setting Only widening conversions are allowed when Option Strict is set to On An integer can be assigned to a decimal A decimal cannot be assigned to an integer A single can be assigned to a double A double cannot be assigned to a single Option Strict On is recommended to help catch errors
Literals- Named Constants Programs often need to use given values For example: dblTotal *= 1.06 Adds 6% sales tax to an order total Two problems with this approach The reason for multiplying dblTotal by 1.06  isn’t always obvious If sales tax rate changes, must find and change every occurrence of .06 or 1.06 Use of named constants resolves both these issues
Named Constants Can declare a variable whose value is set at declaration and cannot be changed later: Const dblSALES_TAX_RATE As Double = 1.06 Looks like a normal declaration except: Const used instead of Dim An initialization value is required By convention, entire name capitalized with underscore characters to separate words The objective of our code is now clearer Const dblSALES_TAX_RATE As Double = 1.06 dblTotal *= dblSALES_TAX_RATE
Displaying Numeric output data To display numeric data, it is necessary to convert the numeric data to String data. The ToString Function and the precision specifier are used together to return a formatted string value. If the number of positions to the right of the decimal in the returned string is less than the number of positions to the right of the decimal in the numeric value being converted, then the returned value is rounded to the specified number of decimal places.
Displaying Numeric output data
Debugging Your Program The three most common types of errors in a program are: format exception, overflow exception and divide by zero exception. Format exception – user enters data in a different format than the program expects and the processes can’t be completed Overflow exception – user enters a value that is greater than the maximum value that can be processed by the statement. Divide by zero – program contains a division operation and the divisor is equal to zero. You can minimize these errors by writing code into your program that checks user input (Chapters 5 & 6)
Visual Basic Debugging Aids You can set breakpoints A line or lines you select in your source code When execution reaches this line, it pauses You may then examine the values in variables and certain control properties You may also single-step through the program which executes one statement at a time This allows you to see and examine: What is happening one statement at a time Where it is happening What the various data values are (Watches) If you would like to learn more about the debugging features in visual studio, follow this link: http://www.codeproject.com/KB/cs/MasteringInDebugging.aspx
Debugging Commands in the Toolbar Visual Studio provides a toolbar for debugging commands MSDN website give you information on how to handle debugging errors http://msdn.microsoft.com/en-us/library/s9ek7a19%28v=VS.90%29.aspx
References Microsoft Visual Basic 2010 Comprehensive. Shelly Cashman. Course Technology.© 2011. 1st edition. Starting out with Visual Basic. Tony Gaddis. Pearson Addison-Wesley .© 2011. 3rd edition Code Project Website. http://www.codeproject.com/KB/cs/MasteringInDebugging.aspx MSN Website. http://msdn.microsoft.com/en-us/library/s9ek7a19%28v=VS.90%29.aspx

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variables
 
Concept of c data types
Concept of c data typesConcept of c data types
Concept of c data types
 
Ppt lesson 07
Ppt lesson 07Ppt lesson 07
Ppt lesson 07
 
Basic
BasicBasic
Basic
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Ppt lesson 08
Ppt lesson 08Ppt lesson 08
Ppt lesson 08
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 
User define data type In Visual Basic
User define data type In Visual Basic User define data type In Visual Basic
User define data type In Visual Basic
 
Introduction To Programming
Introduction To ProgrammingIntroduction To Programming
Introduction To Programming
 
C presentation! BATRA COMPUTER CENTRE
C presentation! BATRA  COMPUTER  CENTRE C presentation! BATRA  COMPUTER  CENTRE
C presentation! BATRA COMPUTER CENTRE
 
Cis160 Final Review
Cis160 Final ReviewCis160 Final Review
Cis160 Final Review
 
Data types in C
Data types in CData types in C
Data types in C
 
Lect 9(pointers) Zaheer Abbas
Lect 9(pointers) Zaheer AbbasLect 9(pointers) Zaheer Abbas
Lect 9(pointers) Zaheer Abbas
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
C data types, arrays and structs
C data types, arrays and structsC data types, arrays and structs
C data types, arrays and structs
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
 
Pengaturcaraan asas
Pengaturcaraan asasPengaturcaraan asas
Pengaturcaraan asas
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
 

Ähnlich wie Variables and calculations_chpt_4

Chapter2pp
Chapter2ppChapter2pp
Chapter2ppJ. C.
 
Introduction to Computer and Programming - Lecture 03
Introduction to Computer and Programming - Lecture 03Introduction to Computer and Programming - Lecture 03
Introduction to Computer and Programming - Lecture 03hassaanciit
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NETJaya Kumari
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICAemtrajano
 
Visual Basics for Application
Visual Basics for Application Visual Basics for Application
Visual Basics for Application Raghu nath
 
Programming concepts By ZAK
Programming concepts By ZAKProgramming concepts By ZAK
Programming concepts By ZAKTabsheer Hasan
 
Visual Basic Fundamentals
Visual Basic FundamentalsVisual Basic Fundamentals
Visual Basic FundamentalsDivyaR219113
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Vahid Farahmandian
 
PLF-Lesson tsu lecture time 2 units-2.pptx
PLF-Lesson tsu lecture time 2 units-2.pptxPLF-Lesson tsu lecture time 2 units-2.pptx
PLF-Lesson tsu lecture time 2 units-2.pptxMattFlordeliza1
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1Ali Raza Jilani
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2dplunkett
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3Vince Vo
 

Ähnlich wie Variables and calculations_chpt_4 (20)

Chapter2pp
Chapter2ppChapter2pp
Chapter2pp
 
Ppt lesson 05
Ppt lesson 05Ppt lesson 05
Ppt lesson 05
 
Lesson 5 PP
Lesson 5 PPLesson 5 PP
Lesson 5 PP
 
Introduction to Computer and Programming - Lecture 03
Introduction to Computer and Programming - Lecture 03Introduction to Computer and Programming - Lecture 03
Introduction to Computer and Programming - Lecture 03
 
Chapter 03
Chapter 03Chapter 03
Chapter 03
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICA
 
Visual Basics for Application
Visual Basics for Application Visual Basics for Application
Visual Basics for Application
 
C++ data types
C++ data typesC++ data types
C++ data types
 
Programming concepts By ZAK
Programming concepts By ZAKProgramming concepts By ZAK
Programming concepts By ZAK
 
Visual Basic Fundamentals
Visual Basic FundamentalsVisual Basic Fundamentals
Visual Basic Fundamentals
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1
 
PLF-Lesson tsu lecture time 2 units-2.pptx
PLF-Lesson tsu lecture time 2 units-2.pptxPLF-Lesson tsu lecture time 2 units-2.pptx
PLF-Lesson tsu lecture time 2 units-2.pptx
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
Data type
Data typeData type
Data type
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3
 
Basic of java 2
Basic of java  2Basic of java  2
Basic of java 2
 
I x scripting
I x scriptingI x scripting
I x scripting
 

Kürzlich hochgeladen

Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Kürzlich hochgeladen (20)

Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

Variables and calculations_chpt_4

  • 1. Variables and Calculations CBIS 112 Ms. Montanez
  • 2. Gathering Text Input In this chapter, we use the TextBox control to gather input the user has typed on the keyboard, learn about the different types of variables types available in Visual Basic and how to use mathematical operators for calculations in a Windows form. At the end of the chapter, you will have completed the Digital Downloads project which entails the following tasks: Collect data from the user through a textbox field Define the Accept and Cancel properties within a form to accept user keyboard behavior to trigger events in a form Convert the text from the textbox field into a number that can use be used in calculations Define the variables needed to calculate the total cost of downloads for the user Debug application to ensure that it works properly
  • 3. The TextBox Control A text box is a rectangular area on a form that accepts input from a keyboard The TextBox control’s Text property can be accessed in code the same way you access other properties
  • 4. Enabling Multi-Line textboxes A Multi-line box will allow the user to enter multiple lines in a textbox. You must resize the textbox vertically to display multiple lines. By clicking on the Action tag, you can enable a textbox to accept multiple lines of text
  • 5. Setting up Masks for fields entered in a textfield A masked textbox allows you to specify a particular format that must be used when entering data in a textbox. Before the user enters data in a form, the masked textbox will display to the user the format of the data to be entered.
  • 6. Keyboard responses in a text fields. Computer users often press the “Enter” key to enter data in a textbox to cause the processing to occur. On the same token, they might attempt to use the “Esc” key as a way to cancel or clear textbox results. To accept this type of user input, it is necessary to setup the Form properties “AcceptButton” and “CancelButton” to the corresponding buttons in a form. 
  • 7. Why Have Variables? A variable is a storage location in the computer’s memory, used for holding information while the program is running The information that is stored in a variable may change, hence the name “variable”
  • 8. What Can You Do With Variables? Copy and store values entered by the user, so they may be manipulated Perform arithmetic on values Test values to determine that they meet some criterion Temporarily hold and manipulate the value of a control property Remember information for later use in the program
  • 9. How to Think About Variables You the programmer make up a name for the variable Visual Basic associates that name with a location in the computer's RAM The value currently associated with the variable is stored in that memory location
  • 10. Declaring Variables A variable declaration is a statement that creates a variable in memory The syntax is: Dim VariableName As DataType Dim (short for Dimension) is a keyword VariableName is the programmer designated name As is a keyword DataType is one of many possible keywords for the type of value the variable will contain Here is an example of a variable declaration: Dim intLength as Integer
  • 11. Declaring Multiple Variables Several variables may be declared in one statement if they all hold the same type of value Dim intLength, intWidth, intHeight as Integer Or this can be done in 3 separate statements Dim intLength as Integer Dim intWidth as Integer Dim intHeight as Integer
  • 12. Variable Naming Rules The first character of a variable name must be a letter or an underscore Subsequent characters may be a letter, underscore, or digit Thus variable names cannot contain spaces or periods (or many other kinds of characters) Visual Basic keywords cannot be used as variable names
  • 13. Variable Naming Conventions Naming conventions are a guideline to help improve readability but not required syntax A variable name should describe its use Each data type has a recommended prefix, in lower case, that begins the variable name The 1st letter of each subsequent word in the variable name should be capitalized intHoursWorked - an integer variable strLastName - a string (or text) variable
  • 14. Setting the Value of a Variable An assignment statement is used to set the value of a variable, as in: Assign the value 112 to the variable length length = 112 Assign the string literal “Good Morning “ followed by the contents of the text box txtName to the variable greeting greeting = "Good Morning " & txtName.Text An assignment changes only the left operand The right operand remains unchanged
  • 15. Visual Basic Data Types Other data types Boolean Char String Date Integer types Byte Short Integer Long Floating-Point types Single Double Decimal
  • 16. Integer Data Types For values that will always be a whole number Usually name a variable starting with a 3 or 4 letter prefix indicating the variable’s type
  • 17. Floating-Point Data Types For values that may have fractional parts Single used most frequently Double sometimes used in scientific calculations Decimal often used in financial calculations
  • 18. Other Common Data Types Boolean – variable naming prefix is bln Holds 2 possible values, True or False Char – variable naming prefix is chr Holds a single character Allows for characters from other languages String – variable naming prefix is str Holds a sequence of up to 2 billion characters Date – variable naming prefix is dat or dtm Can hold date and/or time information
  • 19. The String Data Type A string literal is enclosed in quotation marks The following code assigns the name Jose Gonzales to the variable strName Dim strName as string strName = "Jose Gonzales" An empty string literal can be coded as: Two consecutive quotation marks strName = "" Or by the special identifier String.Empty strName = String.Empty
  • 20. The Date Data Type Date data type variables can hold the date and time or both You can assign a date literal to a Date variable, as shown here: Dim dtmBirth As Date dtmBirth = #5/1/2010# A date literal is enclosed within # symbols All of the following Date literals are valid:#12/10/2010# #8:45:00 PM# #10/20/2010 6:30:00 AM#
  • 21. Assigning Text to a Variable Examples: Declare a string variable to hold thefull name. Dim strFullName As String ' Combine the first and last names' and copy the result to lblFullName strFullName = txtFirstName.Text & " " & txtLastName.Text lblFullName.Text = strFullName
  • 22. Declaring Variables with IntelliSense As you enter your program, VB often aids you by offering a list of choices that could be used at that point After typing "As" in a variable declaration, VB will offer an alphabetical list of all possible data types Type the first few letters of the data type name IntelliSense box will highlight the matching type Press the Tab key to select highlighted choice Or just complete typing the entire data type name
  • 23. Default Values and Initialization When a variable is first created in memory, it is assigned a default value numeric types are given a value of zero Boolean types are given a value of False strings are given a value of Nothing dates default to 12:00:00 AM January 1,1 Good practice to initialize string variables Dim strName as String = String.Empty String with value Nothing causes error if used
  • 24. Initialization of Variables Can provide a starting or initialization value for any type of variable in a Dim statement Usually want to set an initial value unless assigning a value prior to using the variable Just append = value to the Dim statement where value is the literal to be assigned to the variable Dim intMonthsPerYear As Integer = 12
  • 25. Scope and Local Variables Scope refers to the part of the program where: A variable is visible and May be accessed by program code Variables declared within a procedure are called local variables and observe these characteristics Scope begins where variable is declared Extends to end of procedure where declared Variable is not visible outside the procedure A variable cannot be declared twice in the same procedure
  • 26. Performing Calculations Visual Basic has powerful arithmetic operators that perform calculations with numeric variables and literals. Variables used in arithmetic statements in a Visual Basic program must be numeric variables. String data entered by the user must be converted to numeric data before it can be used in an arithmetic statement. A procedure to convert a String data type into an Integer data type is named ToInt32
  • 27. Common Arithmetic Operators Visual Basic provides operators for the common arithmetic operations: + Addition - Subtraction * Multiplication / Division ^ Exponentiation
  • 28. Common Arithmetic Operators Addition dblTotal = dblPrice + dblTax Subtraction dblNetPrice = dblPrice – dblDiscount Multiplication intArea = intLength * intWidth Division dblAverage = intTotal / intItems Exponentiation dblCube = dblSide ^ 3
  • 29. Arithmetic Operator Precedence Operator precedence tells us the order in which operations are performed From highest to lowest precedence: Exponentiation (^) Multiplicative (* and /) Integer Division ( Modulus (MOD) Additive (+ and -) Where precedence is the same, operations occur from left to right
  • 30. Grouping with Parentheses Parentheses () can be used to force selected parts of an expression to be evaluated before others Assume we’re computing the average of 3 numbers dblAvg = int1 + int2 + int3 / 3 ' incorrect int3 / 3 is evaluated first That result is added to int1 and int2 Use parentheses to control order of operations dblAvg = (int1 + int2 + int3) / 3 ' correct int1 + int2 + int3 is evaulated first That result is divided by 3 When in doubt, use parentheses!
  • 31. Converting Mathematical Expressions to Programming Statements In algebra, the mathematical expression 2xy describes the value 2 times x times y. Visual Basic requires an operator for any mathematical operation.
  • 32. Mixing Different Data Types When you assign a value of one data type to a variable of another data type, Visual Basic attempts to convert the value being assigned to the data type of the receiving variable.
  • 33. Option Strict Option Strict is a VB configuration setting Only widening conversions are allowed when Option Strict is set to On An integer can be assigned to a decimal A decimal cannot be assigned to an integer A single can be assigned to a double A double cannot be assigned to a single Option Strict On is recommended to help catch errors
  • 34. Literals- Named Constants Programs often need to use given values For example: dblTotal *= 1.06 Adds 6% sales tax to an order total Two problems with this approach The reason for multiplying dblTotal by 1.06 isn’t always obvious If sales tax rate changes, must find and change every occurrence of .06 or 1.06 Use of named constants resolves both these issues
  • 35. Named Constants Can declare a variable whose value is set at declaration and cannot be changed later: Const dblSALES_TAX_RATE As Double = 1.06 Looks like a normal declaration except: Const used instead of Dim An initialization value is required By convention, entire name capitalized with underscore characters to separate words The objective of our code is now clearer Const dblSALES_TAX_RATE As Double = 1.06 dblTotal *= dblSALES_TAX_RATE
  • 36. Displaying Numeric output data To display numeric data, it is necessary to convert the numeric data to String data. The ToString Function and the precision specifier are used together to return a formatted string value. If the number of positions to the right of the decimal in the returned string is less than the number of positions to the right of the decimal in the numeric value being converted, then the returned value is rounded to the specified number of decimal places.
  • 38. Debugging Your Program The three most common types of errors in a program are: format exception, overflow exception and divide by zero exception. Format exception – user enters data in a different format than the program expects and the processes can’t be completed Overflow exception – user enters a value that is greater than the maximum value that can be processed by the statement. Divide by zero – program contains a division operation and the divisor is equal to zero. You can minimize these errors by writing code into your program that checks user input (Chapters 5 & 6)
  • 39. Visual Basic Debugging Aids You can set breakpoints A line or lines you select in your source code When execution reaches this line, it pauses You may then examine the values in variables and certain control properties You may also single-step through the program which executes one statement at a time This allows you to see and examine: What is happening one statement at a time Where it is happening What the various data values are (Watches) If you would like to learn more about the debugging features in visual studio, follow this link: http://www.codeproject.com/KB/cs/MasteringInDebugging.aspx
  • 40. Debugging Commands in the Toolbar Visual Studio provides a toolbar for debugging commands MSDN website give you information on how to handle debugging errors http://msdn.microsoft.com/en-us/library/s9ek7a19%28v=VS.90%29.aspx
  • 41. References Microsoft Visual Basic 2010 Comprehensive. Shelly Cashman. Course Technology.© 2011. 1st edition. Starting out with Visual Basic. Tony Gaddis. Pearson Addison-Wesley .© 2011. 3rd edition Code Project Website. http://www.codeproject.com/KB/cs/MasteringInDebugging.aspx MSN Website. http://msdn.microsoft.com/en-us/library/s9ek7a19%28v=VS.90%29.aspx