Unit 2 Variables and Functions: Structure

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

UNIT 2 VARIABLES AND FUNCTIONS

Structure

2.0 Introduction
2.1 Objectives
2.2 What are Variables?
2.3 Variable Names
2.4 Variable Types
2.5 Range of the Yariable Values
2.6 Functions
2.6.1 String Functions
2.6.2 Financial Functions
2.6.3 Numeric Functions
2.7 Summary

2.0 INTRODUCTION

In this chapter you will learn about variables, values and the different kinds of data types which you
can use in Visual Basic. In every computer language, the programs manipulate data that is stored in
variables. The variables have different attributes and can hold different types of data. The variables
used in this language perform the same operation what the variables do in any other language i.e.
variables i.e. store the numbers or string of characters. By declaring a variable to be of certain data
type, the Visual Basic gets to know the kind of data this variable holds. The variables are not only
used to assign the values, but they also at time help in debugging your programme. The values can
be declared through these variables and once they get assigned to these variables, they can be
referred in the application programme.

2.1 OBJECTIVES

After studying this unit, you will be able to:

Define a variable and how to name a variable;

Discuss types and ranges of variables;

Explain different functions and their applications.

2.2 WHAT ARE VARIABLES?

Variables are nothing but different names used for temporary storage of data. While selecting the
names for the variables, one has to keep in mind that no reserved words or key words are used. The
variables are stored in memory. Each program in windows has its own area of memory for variables Variables &
storage that it uses and works with. Functions

Variables are places where you can store any type of data whether it is a number or a string, which
you can use in your programs to keep track of intermediate results. The value of these variables can
be changed during the execution of the program. The testing of the different variables and their
values can be best done in the Debug window:

This command does not display anything on the screen.

The equal to (=) sign is another operator called the assignment operator as it assigns the desired
value to the variable name given. This is not an equation. This means that the result of the addition
of 2 & 9 i.e. 1 1 is assigned to the variable C. In the next line you see, TaxRate = 0.7 i.e. the value of
this variable is 0.7. The assignment operator reserves a place in a part of your computer memory
and gives a name C or TaxRate to it, and whenever you want to show this value, you can use the
Print command to display the value stored in a variable by supplying the variable name.

PRINT C , TaxRate mi

In case you wish to change the value of the TaxRate at some later stage to 0.65, it can be done by
simply assigning the value 0.65 to the variable name TaxRate and frop this point onwards the
application programme shall assume the value of Taxrate as 0.65.

You can do the calculations with these variables using arithmetic operators.
Components of
Windows
Programming
& Visual Basic

How Visual Basic works with variables?

Whenever you typed V=3, Visual Basic first looks through its memory for a variable named V, If
this variable did not exist, it creates a new variable with the name V at some memory location. If
the variable already exists in the memory, it will do all operations of variable at the same location
of memory. While working with variables, there is one important aspect one has to keep in mind,
whenever you leave the run mode(while the application is running), Visual Basic frees the memory
location of these variables. If you again go in the run mode of the visual basic, it again creates the
variables in the memory whichever you want to create.

VARIABLE NAMES

The only variable name so far we have used is V but you can actually use much longer and more
descriptive variable names. When you are naming variables, you should follow certain rules. These
rules are:

1. The variable name length must be 1 to 40 characters long.

2. You can use both upper or lower case letters, numbers and combination of letters & numbers
and the underscore. While using combination of both letters and numbers the precaution to be
taken is that the variable name must start with a letter.

3. You cannot use command names (i.e. the reservedor key words) as the variable name like Beep
or Print because these are keywords of the language.

The following examples give you an idea, how to create variable names:

FirstName It is mixed case, the variable name starts with an upper case character

firstname It is also mixed case but the variable name starts with a lower case character

first-name One can use underscore in the name to make the variable meaningful

Name3 One can also include a number in the variable name but not as first character
The following names are not valid: Variables &
f Functions

3Name variable cannot have names that start with a number

print variable cannot have the same name as command words

2.4 VARIABLE TYPES

Variables can have any type of value i.e. a number. a string. an integer. a boolean etc. You have
seen that the variables can contain either a number or a string. This means that a variable can have
I
any type of value. Visual Basic also lets you choose whether or not to declare your variables. If you
are not declaring the type of the variable, Visual Basic automatically declares it as a variant i.e. the

I
variant can contain byte, Boolean, Integer, date, String etc.. One problem which is created in case
you do not declare the type and make it variant is these variables add significant overheads to the
program and waste lot of memory and makes the mathematical calculations slow. One can also
create other types of variables that are more restrictive. You have to define the type of value i.e. a
numeric or string, the variable can contain. If you define a variable to have a string type value, then
that variable can only contain that type of value and you cannot do any arithmetic operation with
such a variable.

You can tell Visual Basic that a variable has a specific type by adding a special character at the ehd
of the variable name. No spaces are to be left between the name and the special character used.
Different special characters are used to indicate various types of variables.

Operator XME Contents

% Integer Integer

& Long inieger Integer

! Single Floating Point Number

# Double Floating Point Number

@ Currency Number with Fixed Decimal Point

$ String Character String

(none) Variant (Any of the above) Any data

Adding a dollar sign ($) at the end of a variable name implies that the variable is a string
Components of SOif YOU type:
Windows
Programming
Sr Visual Basic

This will mean, "s" is a string variable.

If you type:

It gives an error message

Similarly other special characters can also be used.

2.5 RANGE OF THE VARIABLE VALUES

You have seen various types of variables and how they can be created. But there are some limits
within which the value one can assign to a variable.
Operator Lim& Memory Storage Variables C
-- 'Type Functions
Yo 1nteger -32,768 to 32,767 2 bytes
& Long -2,147,483,648 to 2.147,483,647 4 bytes
! Single -3.402823E38 to - 1.401298E-4.5 for 4 bytes
negative values.
1.401298E-45 to 3.402823E38 for positive
values
Double -.797693 13486232E308 to - 8 bytes
4.94065645 84 1247E-324 for negative
values
4.9406564584 1247E-324 to
1.79769313486232E308 for positive values

C'urrmc> -922,337,203.685,477.5808 to 8 bytes


922.337,203,685,477.5807
String From 0 to 65,400 characters for Windows 10 bytes + string length
3.1 and 0 to 2 billion characters for
Windows 95
(none) Variant Any of the above 16 bytes for numeric and
22 bytes + string length
for character
I
i When you try to multiply two large integer numbers together:
i

a warning message appears in the message box showing "overflow". Overflow means that the
result is too large to be assigned to a variable as an integer.

The above csarnple result is 960,000,000, which i s outside the limits of an integer variable.

If one tries to divide by a zero value, then also one gets an error message as it is not permitted in the
arithmetic operation to divide any value by zero. Look at another example of integer, type:
Components of
Windows
Programming
& Visual Basic

It gives you an error message as shown in the picture below.

If you have the large number and you want to do some arithmetic calculations, you can do so by
following the procedure given in the following example:

n! = 2000000
PRINT n!
2000000

You can assign the large value to a variable and then do the multiplication with this:

This will not give you any error. You can see the result also:
Variables &
Functions

ÿÿ he answer l.OE+lO is in scientific notation. It means 1.0 multiply by 10" (10 to the power of 10).
Since this is not possible to write this numberon a computer, it uses scientific notation.

How computer stores these values internally?

The computer memory is divided into number of small storage locations called bytes. Each byte can
hold a single character of information. To store a character in the memory location, a string of
characters requires one byte for each character, plus a few extra bytes that keep track of how many
characters are there in the string.

The numbers (integer) would require one byte for each digit in the number, but there's actually a
much more efficient way to store numbers. Therefore, a single byte can represent any number
between 0 and 255 and two bytes together can represent any positive number between 0 and 65,535.
Actually, half the numbers are defined as negative, producing a range of -32,768 and 32,767,
exactly the range allowed by an integer type. Thus, an integer is exactly two bytes long.

2.6 FUNCTIONS

While programming, at times it is required to convert a variable of a particular type to another type
for concatenation purposes.. Visual Basic provides some related functions for conversion between
the different types of variables, which help you in working with Visual Basic. Thus a function can
be defined as a procedure which performs a particular action and then returns a value. Visual Basic
has number of built-in functions that help the programmer to write efficient programmes.

2.6.1 String Functions

The string functions (as the name itself indicates) are those functions, which perform the desired
action on the character strings. These character strings known as the arguments of the function can
be enclosed in the parentheses () following the function name. Following table gives the string
functions in Visual Basic.

Function Meaning

Str To convert number values to string values

Lcase$ To return a text string with all characters converted to lowercase


Components of
Windows Function Meaning
Programming
& Visual Basic
Ucase$ To returns a text string with all characters converted to uppercase

RtrimS To build a text string with all the spaces at the end of the string removed

Ltrim$ To build a text string with all the spaces at the start of the string removed

Len To return the length of the string i.e .number of characters of a string

Following example shall explain how to use Ucase() function.:

This UcaseO function is used to return an uppercase version of a string of the contents put in 0.

TestString = "Hello Mr India" ' String to convert.

TestUpperCase = UCase(testString) ' Returns "ELL0 MR INDIA".

(Here "TestString" aiid "TestUpperCase" are two variable names used).

The Ltrim() and RtrimO functions can be used to remove spaces leading the text string and
trailing spaces at the end of the test string respectively i.e. if there are any blank spaces either before
of after the variable, those can be removed. If the spaces are at both the ends i.e. at the beginning
and at the end of the variable then, the T r i m 0 function alone can be used to strip both leading and
trailing spaces.
teststring = " INDIA " ' Initialize string.
LeftTrimString = LTrim(TestString) ' LeftTrimString = "INDIA " .
RightTrimString = RTrimCTestString) RightTrimString = " INDIA"

Trimstring = LTrim(RTrim(TestString)) ' Trimstring = "NDIA"


' You can achieve the same result by using
Trim function alone.

Trimstring = Trim(TestString) 'TrimString="lNDlA".


(Here ' ~ e s k t r i n ~&""Trimstring" are two variable names used.)

2.6.2 Financial Functions

These functions are used to perform actions relating to financial accounting. The table below gives
some of the financial functions used in the language.

Rate Function To returns the interest rate.

e.g.:

To calculate the interest rate of a loan:


Variables &
Functions

Where TotPmts is Total number of payments, Payment is loan amount, .


Principalval is principal amount, Future Val is future value, PayDuration
?.'B
is payment period and Result is expected interest rate.
. $.,
3
t Q
;?A
K g
.:>*
.:-

: ;.q2
.Q
:i DDB Function To returns the depreciated value of an asset for a specific duration using
:I;
Ry
ii the double-declining balance method or some other method you specify.
;, i
.p '"

2 4:
%'<3
t i &+
i
. .=
,5,' s 2
FV Function To returns the future value based on periodic, constant payments and a
?$
+$4
. constant interest rate. e.g.:
8
:'?j
,.>

? ...:r
. To return the future value of an investment:
,,'$A
: $;
54
.,. Q
FutureVal = FV(APR / 12, TotPmts, -Payment, -PrincipalVal,
4
1.5,
PayDuration)
g$
$+,J

@ Where APR is expected interest annual percentage rate, PrincipalVal is he


$3
..-.A current value of the investment.
g3
$4
,<>V.
To returns the payment based on periodic, constant payments and a
Pmt Function
:,+
;.j
.
:
, :,*
... constant interest rate.
1
3,;

e.g.:Payment = Pmt(APR / 12, TotPmts, -PrincipalVal, FutureVal,


., e;'
$?$ PayDuration)
g$
28j
'g$& PV Function To returns the present value based on periodic, constant payments to be
*:
.w4 paid in the future and a constant interest rate. e.g.:
$;!
$;I
7-1

:if
>$d PrincipalVal = PV(APR, TotPmts, -YrIncome, FutureVal, PayDuration).
3: :<,
?~?<
h;J
@'
,. $4
'3
y$&
.,
g:
A

&;~ 2.6.3 Numeric Functions


g.

The numeric functions are those functions which perform actions related to numbers. Following
table gives some of the numeric functions used in Visual Basic.

Val To convert Character String to Number

CLng To convert Number to Long

Ccur To convert Number to Currency

CDbl To convert Number to Double

GSgn To convert Number to Single


Components of For Example:
Windows
Programming
&Visual Basic This CcurO function is used to convert an expression to a Currency.

TestDouble = 543.2 14588 ' TestDouble is a Double.


TestCurr = CCur(TestDoub1e) Convert result of TestDouble

' (543.214588) to
'Currency (543.214588).

Check Your Progress

Load Visual Basic and you try following exercise one by one. Watch the result on your monitor.

1. Use the special characters explained in the chapter to store 1000 as an Integer type variable.

2. Try to store 500 in String type variable. If you are not usihg quotes, see what happens.

3. Use a variable name and store 'INDIA EDUCATION CENTRE' as String type variable.

4. Now try to store the above string as an Integer type variable.

5. Try to convert the variable of question 3 to lower case characters using the function.

6. Using all the types of Trim functions explained, try to left trim, right trim and trim the character
string ' INDIA EDUCATION CENTRE 7

7. Try to store 300.00314 as Integer type variable and then try to multiply this number by lo6. See
what happens.

2.7 SUMMARY

In this chapter you have been exposed to the variables, their usage and the functions & various
types of functions. To summarise:

Variables are places where one stores any type of data i.e. whether it is a number or a character
string, that can be used in a program to keep track of intermediate results.

Variable Names:

3 Name length can be maximum of 40 characters long.

3.It can contain any of the upper or lower case characters, numbers and the underscore. In
case the combination of numbers and characters are to be used as variable name, the first
character must be a character.
3 No keyword or reserved word or the command names can be used as variable names i.e. Variables &
Functions
Beep or Print etc can not be used since these are keywords of the language.

Variables should be defined as one of the specific type like numbers or string. If the type is not
defined, Visual Basic automatically declares it as a Variant.

Visual Basic provides number of functions like string function, financial functions and numeric
functions for conversion between the different types of values.

You might also like