Variables / Scope. Variable Memory location whose value can change as the program is running. Used to hold temporary information Used to control the type.

Slides:



Advertisements
Similar presentations
Tutorial 31 Variable Memory location whose value can change as the program is running. Used to hold temporary information Used to control the type of data.
Advertisements

Operators & Identifiers The Data Elements. Arithmetic Operators exponentiation multiplication division ( real ) division ( integer quotient ) division.
Chapter 3: Using Variables and Constants
Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition.
1.
String Variables Visual Basic for Applications 4.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Data Types and Operations Programming Fundamentals (Writing Code)Programming Fundamentals (Writing Code)
Chapter 2: Introduction to C++.
CIS 115 Lecture 5.  A storage location in memory (RAM)  Holds data/information while the program is running  These storage locations can be referred.
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
Variables and Constants
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
CS0004: Introduction to Programming Input and Output.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Lecture 8 Visual Basic (2).
Access VBA Programming for Beginners - Class 2 - by Patrick Lasu
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
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.
Variable, Constants and Calculations Dr Mohammad Nabil Almunawar.
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.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
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)
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
Variables in VB.NET. Variables  A storage location in memory (RAM)  Holds data/information while the program is running  These storage locations can.
1 Writing Software Kashef Mughal. 2 Algorithms  The term algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving a problem.  An Algorithm.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Tutorial 81 Field, Record, Data File Field - a single item of information about a person, place, or thing Record - a group of related fields that contain.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
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.
Introduction to Computer CC111 Week 09 Visual Basic 2 Visual Basic Variables 1.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
1.
Egyptian Language School Computer Department
A variable is a name for a value stored in memory.
VBA - Excel VBA is Visual Basic for Applications
Visual Basic Variables
Visual Basic 6 (VB6) Data Types, And Operators
Data Types, Arithmetic Operations
Chapter 3: Using Variables and Constants
2. Understanding VB Variables
IDENTIFIERS CSC 111.
Microsoft Visual Basic 2005 BASICS
Chapter 6 Variables What is VBScript?
Numbers.
CIS16 Application Development Programming with Visual Basic
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
CHAPTER FOUR VARIABLES AND CONSTANTS
Chapter 2: Introduction to C++.
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Variables and Constants
Presentation transcript:

Variables / Scope

Variable Memory location whose value can change as the program is running. Used to hold temporary information Used to control the type of data used in calculations –Val returns a Double-type, which is often larger than necessary Can store only one piece of data at any time Data is processed faster

Data Types Byte Boolean Currency Date Double Integer Long Object Single String Variant

Use the Appropriate Data Type Integer or Long - Used to store whole numbers Single, Double, Currency - Used to store numbers with a decimal fraction String - Used to store strings Boolean - Used to store Boolean values (True and False) Date - Used to store date and time information Object - Used to store a reference to an object Byte - Used to store binary data Variant - Flexible, but not efficient

Variable Names Should be meaningful First three characters should represent the data type Remainder of name should represent the variable’s purpose

Three-character Ids Byte byt Booleanbln Currency cur Date/Time dtm Doubledbl Integerint Longlng Objectobj Singlesng Stringstr Variantvnt

Rules for Naming Variables Name must begin with a letter. Name can contain only letters, numbers, and the underscore. No punctuation characters or spaces are allowed. Name cannot exceeds 255 characters. Name cannot be a reserved word.

Creating (declaring) a Variable Dim variablename [As datatype] Public variablename [As datatype]

Assigning Values to Variables Assignment statement –variablename = value Examples: –sngHours = 38.5 –curBonus = curSales *.1 –strName = “Susan”

Constants Literal constant –an item of data whose value cannot change while the program is running Examples: –7 – “Janet” Symbolic constant –a memory location whose contents cannot be changed while the program is running Examples: –conPi –conRate

Scope of a Variable Indicates which procedures can use the variable Determined by where the Dim or Public statement is entered. Can be either global, form-level, or local.

Variable Scope Global Variable: Defined using a Public declaration in the general declarations section of a module Module/FormVariable: Defined using a Private or dim declaration in the general declarations section of a module or a form Local Variable: defined using dim or static within a subprocedure or function In general, when variables have the same name but different scope, the most local (closest) variable is used.

Local Variables Created with the Dim statement. The Dim statement is entered in an object’s event procedure (within a subprocedure or function) Only the procedure in which it is declared can use the variable. Same name can be used in different procedures Removed from memory when the procedure ends.

Form-level Variables Created with the Dim statement. The Dim statement is entered in a form’s General declarations section. Can be used by any of the procedures in the form. initialized when module/form is first opened Removed from memory when the application ends.

Global Variables Created with the Public statement. The Public statement is entered in a code module’s General declarations section. initialized when program starts Used in multi-form projects and can be used by any of the procedures in any of the project’s forms. Removed from memory when the application ends.

Static Variables Static variables –defined using static instead of dim within a subprocedure or function –acts like a local but is initialized only on first use

Static Variable example Goal: count the number of times a routine is entered private sub command1_click() dim counter as integer counter=counter+1 debug.print counter end sub Does NOT work unless counter is declared using static instead of dim

Local vs Static Variables A local variable is defined in an event procedure, and it is removed from memory when that event procedure ends. A static variable also is defined in an event procedure, but it retains its value when that event procedure ends. A static variable is a special type of local variable.

Swapping To swap the contents of two variables: –assign the first variable’s value to a temporary variable –assign the second variable’s value to the first variable –assign the temporary variable’s value to the second variable

Option Explicit Statement Doesn’t allow you to create variables “on the fly.” Enter in every form’s, and every code module’s, General declarations section. Use Tools, Options, Environment tab, Require Variable Declaration to have Visual Basic include Option Explicit in every new form and module.

Creating a Symbolic Constant A memory location whose value cannot change during run time. Syntax: [Public] Const constname [As datatype] = expression Examples: –Const conPi As Single = –Public Const conMaxAge as Integer = 65

Scope of a Symbolic Constant Indicates which procedures can use the symbolic constant. Global: Public Const statement in a code module’s General declarations section. Form-level: Const statement in the form’s General declarations section. Local: Const statement in an event procedure.

Numeric Types Integer - 2 bytes of memour –a 16-bit signed integer –whole number between and long - 4 bytes of memory –a 32-bit signed integer (+/- 2^31) – whole number between 2,147,483,648 and 2,147,483,648 single - 4 bytes of memory –a single-precision decimal floating point number –+/ e-45 to e38 double bytes of memory –a double-precision decimal floating point number –+/ e-324 to e208

Arithmetic Operations (1) n=5 integer (long or short) or floating point y=a+b y=a-b, y=a*b (add/subtract/multiply) z=x / y divides two numbers and returns a floating point z=x mod y divides two numbers and returns only the remainder. z=x \ y divides two numbers and returns an integer result

Arithmetic Operations (2) isnumeric(thing) returns TRUE if thing is numeric randomize(number) initializes the random number generator n=rnd(x) returns random number 0 <= x < 1 s=str(number) converts a number to a string n=val(string) converts a string to a number n=rgb(red,green,blue) returns RGB color value n=sgn(x) returns 1,0,-1 if x is pos., zero, neg.

Boolean Operations (1) Consume 2 bytes of memory result = exp1 And exp2 –true only if both exp1 AND exp2 are true result = expression1 or expression2 –true if either or both exp1 OR exp2 are true result = NOT exp1 –true if exp1 is false, false if expression is true

Comparisons x y, x>y, x>=y where x, y can be strings or numbers y = a is b returns true if a & b are the same object y = string like pattern y=StrComp(string1, string2[, compare]) compares two strings based on the compare type typeof object returns an object's type –Can only be used as part of an if statement if typeOf thing is label then thing.backcolor=vbGreen

String Operations

String Manipulation Functions Left(string, length) –returns the leftmost length characters in the string Right(string, length) –returns the rightmost length characters in the string Mid(string, start[, length]) –returns length characters from string, beginning with start

Instr Function Instr(start, string1, string2[,compare] –start is a numeric expression that sets the starting position for the search –string1 is the string expression being searched –string2 is the string expression being sought –compare is either 0 (default; case-sensitive) or 1 (case-insensitive) –returns the starting position of string2 within string1

Trim, LTrim, RTrim Trim(string) - removes leading and trailing spaces from a string LTrim(string) - removes leading spaces from a string RTrim(string) - removes trailing spaces from a string

String Concatenation Ampersand - & Examples: (Assume strFirstName contains “Mary” and sngSales contains 1000) –“Hello “ & strFirstName –strFirstName & “ sold $“ & sngSales & “.” Results: –Hello Mary –Mary sold $1000.

String Operations (1) Strings consume 0-2 Billion bytes of memory, but on;y as much as needed - very efficient s=“Strings are always defined in quotes” & - String coercion and concatenation s=str(number) converts the number to a string n=val(string) tries to convert the string to a number s=ucase(string) converts string to upper case s=lcase(string) converts string to lower case string1=lset(string2) left justifies string2 in string1with trailing spaces (there is also an rset)

String Operations (2) n=asc(string) converts first character to a ASCII character code s=chr(character-code) returns a string containing the respective character s=hex(num) returns the hex value of num as a string (oct returns octal value) s=inputbox(prompt, title) Displays a prompt in a dialog box, waits for the user input and returns a String containing the contents of the text box

String Operations (3) n=len(string) returns integer length of string s=ltrim(string) removes leading spaces s=rtrim(string) removes trailing spaces s=trim(string) removes surrounding spaces s=space(n) returns a string of n spaces s=left (string,n) returns the left n characters of string s=right(string,n) returns the right n characters of string

String Operations (4) s=mid(string,start,n) Returns n characters beginning at character #start Mid(stringvar, start[, n]) = str2 replaces n characters in stringvar with characters in str2 n=InStr(string1, string2) searches for string2 inside string1 and returns the integer position of the start s=string(n,char) returns an n-character string filled with char

Date / Time / Misc

Date/Time related Statements Date Data Types consume 8 bytes of memory Date comparison - if somedate < #12/31/1993# then …. d = Now - returns system date and time as date type d = date - returns system date as date type d$ = date$ - returns system date as string d = time - returns system time as a date type time = valid-time - sets the system time !!!!!!!!!!!!! d$ = time$ - returns system time as a string i = timer - integer number of seconds since midnight n=weekday|month|day|year (date) Returns whole number representing the weekday|month|day|year

DateAdd() – Add value to a date DateDiff() – Returns difference between 2 dates DatePart() – Return parts from a date Dim FirstDate As Date Dim K As String Dim N As Integer Dim Msg k= "m" ‘we will be adding months to our date FirstDate = InputBox("Enter a date") ‘like 9/1/2001 N = InputBox("Enter number of months to add") Msg = "New date: " & DateAdd(k, N, FirstDate) MsgBox Msg The above program will return 12/1/2002 when we add 15 (months) to 9/1/2001. If k =“d”, and it will add days.

Misc beep - beeps the computer’s speaker (sort of) n=vartype(variable) returns an integer corresponding to variable type n=rgb(red,green,blue) sets n to a long integer representing a color made up of red, green, blue (0-255). 0,0,0 = black 255,255,255 = white n=qbcolor(x) where x is one of the 16 Quick Basic colors 0-15