Showing posts with label vb functions. Show all posts
Showing posts with label vb functions. Show all posts

Wednesday, April 14, 2010

Script to print Prime Numbers

Click on Back to the Assignment Question Page

Write a script to print prime numbers based on the user input for the prime number limit.

n = Inputbox("Please Enter the limit")
For i = 1 to n
aaaCount = 0
aaaa = 1
aaaaaaDo While a<=i
aaaaaaaaaIf i MOD a = 0 Then
aaaaaaaaaaaaCount = Count + 1
aaaaaaaaaEnd If
aaaaaaa=a+1
aaaaaaLoop
aaaaaaaaaIf Count = 2 Then
aaaaaaaaaaaavar = var&" "&i& ", "
aaaaaaaaaEnd If
Next
aaaMsgBox("Prime numbers within " &n&" numbers = :" &var)

Click on Back to the Assignment Question Page

Write a VB Script to Print different Operations using Select Statement

Click on Back to the Assignment Question Page

This Code gives an idea as to how we can use FOR loop in our script to make it more meaningful and reduce the no of lines of code.


Hope you remember the SELECT CASE statement in which we have looked at a code where in the user can perform a particular type of operation like addition, subtraction, multiplication and division. Now using the For loop try to ask the user how many times the operation should perform. For ex if the user enters 3 then the code should run for three times.

Look the script for this Select Case Statement

The script for this is given below. What i have done is that before the user to select the operation before this line we will add few code like an inputbox and a for loop. The code to be added in the top is like this and at the end of the code add NEXT. Now we are asking the user how many times the user wants to perform the operations and taking that value in the variable Varint1 and converting it into integer. Remember that by default a variant is a string. Then we are passing the value into the for Loop and incrementing by one value.

Varint1 = CINT(Inputbox("Enter the number of times this operation to be performed"))
For i = 1 to Varint1 Step 1
Look at the entire code
Varint1 = CINT(Inputbox("Enter the number of times this operation to be performed"))
For i = 1 to Varint1 Step 1
UserInput = Inputbox("Enter any of the following options"&vbnewline&" " &vbnewline&"1 for Addition"&vbnewline&"2 for Subtraction"&vbnewline&"3 for Multiplication"&vbnewline&"4 for Division")
Var1 = CINT(Inputbox("Enter the First Value"))
Var2 = CINT(Inputbox("Enter the Second Value"))
aaaSelect Case UserInput
aaaCase 1
aaamsgbox"The Sumation of "&Var1& " and " &var2& " is: "&Var1 + Var2
aaaCase 2
aaamsgbox"The difference between "&Var1& " and " &var2& " is: "&Var1 - Var2
aaaCase 3
aaamsgbox"The product of "&Var1& " and " &var2& " is: "&Var1 * Var2
aaaCase 4
aaamsgbox"The quotient between "&Var1& " and " &var2& " is: "&Var1 \ Var2
aaaCase Else
aaamsgbox "Invalid entry"
aaaEnd Select
Next
Click on Back to the Assignment Question Page

VB Scripting - FOR Looping Construct

Previous11121314151617181920Next


FOR Looping Constructs in VB Scripting


For Loop is used to run a piece of code iteratively for a finite number of times. The start and end conditions are known in advance and the counter automatically increments by one and this increment is by default.

FOR Looping Construct Example

Syntax

For [condition]
Code
Next

A simple for loop example

For i = 1 to 10
Msgbox "This loop is repeated "&i& " times"
Next

When you run this script the message box will display “This loop is repeated 1 times” and as you click the number increments till it reaches 10 times and also in the message the number is incremented and displayed.

For Step Next Looping Construct


In this kind of looping construct we actually change the increment to the desired number and the increment happens as we desire. To change the default increment value we use “STEP” along with the For Loop or you can have user defined increment like i=i+1 etc.

Syntax

For [condition] Step [increment/expression]
Code
Next


Example: We will use the above example and change the increment value as desired.

For i = 1 to 10 Step 2
Msgbox "This loop is repeated "&i& " times"
Next

Now when you run the script the value is incremented by 2 and the value in the message box will change and will display as “This loop is repeated 1 times” initially and then the value changes to 3,5,7,9 and the script terminates because next value is 11 and is greater than 10.

Assignment to do for FOR Looping Construct


1. Hope you remember the SELECT CASE statement in which we have looked at a code where in the user can perform a particular type of operation like addition, subtraction, multiplication and division. Now using the For loop try to ask the user how many times the operation should perform. For ex if the user enters 3 then the code should run for three times.

Look the script for this Select Case Statement

Click Here to view the Answer

2. Write a script to print prime numbers based on the user input for the prime number limit.

Click Here to view the Answer

3. Write a script to generate the Fibonacci series. Again ask the user for the limit.

Click Here to view the Answer

4. Write a script to print all the odd numbers till 100. Do not use the STEP statement.

5. Write a script to convert degrees to Fahrenheit.


Previous11121314151617181920Next

VB Scripting - Looping Constructs

Previous11121314151617181920Next

Different types of Looping Constructs in VB Script and its usage in VB Scripting.


Looping constructs allows a user to run a group of statements or piece of code repeatedly that many times as desired by the user. There are some loops which repeat statements until the condition become false and others loops which repeat statements until the condition becomes true. Also there are those loops which repeat statements for a specific number of times.

There are different kinds of looping construct and based on the requirements we can use any of this Looping constructs. The are basically two types of looping constructs FOR and DO. Let’s look at them

FOR Looping Construct

1. For Next Loop
2. For Step Next Loop
3. For Each Next


DO looping Constructs

1. Do Loop While
2. Do Loop Until
3. Do While Loop
4. Do Until Loop
5. While WEnd Loop


Previous11121314151617181920Next

VB Scripting - Constants - Built In Constants

Previous11121314151617181920Next


What is a Built in Constant in VB script?

Built in Constants are those which are already created and stored in VB Library and they cannot be changed and they can be used as it is for various purposes. They in turn help you to print information with meaning and also messages with some action.



Different types of Built in Constants

Please find the list of built in constant and their meaning.

Built in ConstantsWhat it does
vbOKOnlyOK button only
vbOKCancelOK and Cancel buttons
vbAbortRetryIgnoreAbort, Retry, and Ignore buttons
vbYesNoCancel Yes, No, and Cancel buttons
vbYesNoYes and No buttons
vbRetryCancel Retry and Cancel buttons
vbCritical Critical Message icon
vbQuestion Warning Query icon
vbExclamation Warning Message icon
vbInformation Information Message icon
vbDefaultButton1 First button is default
vbDefaultButton2 Second button is default
vbDefaultButton3 Third button is default
vbDefaultButton4 Fourth button is default
vbApplicationModal Application modal i.e. the current application will not work until the user responds to the message box
vbSystemModal System modal i.e. all applications wont work until the user responds to the message box


Example

Const TEST = "Are you sure you want to exit"
msgbox TEST, vbYesNo

The message box displayed will be like this with Yes and No buttons.



Previous11121314151617181920Next

VB Scripting - Constants

Previous11121314151617181920Next

Constant in VB Scripting is a meaningful and specific name that takes the place of a data type like integer or string and never changes. There are two types of constants.



1. Named Constant
2. Built in Constant

Constant is like a variable but unlike variable the value does not change for the constant. It is a permanent value stored in the memory.

Named Constant

You will actually assign a integer or a string to a variable but the value assigned to this variable cannot be changed. It is like a variable but not behave like a variable. The value does not change and it cannot be used as a variable.

As part of the coding convention it is better to write all the constants in upper case even though VB Scripting is case insensitive but for easy understanding it is written and this makes no difference.

Note: The variables are written in lower case. A constant cannot be used as a variable.

You can create user defined constants using the const statement and can be created on numeric and string values giving meaningful names.

Syntax

Const [Name] = [Expression]


Const GREETING = “Welcome to the world of constants”
Const Age = 50


Example

Const GREETING = “Welcome to VB Scripting”
Msgbox GREETING


Previous11121314151617181920Next

Tuesday, April 13, 2010

VB Scripting - Select Case

Previous11121314151617181920Next

Select Case statement in VB Scripting is also a branching statement. We branch out the code by evaluating one expression. Select Case is an alternative for If Else. Select Case can be used invariably (any where)



Syntax for Select Case Statement


Select Case [condition]
Case 1
aaaCode
Case 2
aaaCode
Case 3
aaaCode
Case Else
aaaCode
End Select


Example to understand it easily


Let us write a script which can display the resultant value of two integers based on the selection made. We are computing Addition, Subtraction, Multiplication and division of the two integers and based on the user selection the operation is performed.

UserInput = Inputbox("Enter any of the following options"&vbnewline&" " &vbnewline&"1 for Addition"&vbnewline&"2 for Subtraction"&vbnewline&"3 for Multiplication"&vbnewline&"4 for Division")

Var1 = CINT(Inputbox("Enter the First Value"))
Var2 = CINT(Inputbox("Enter the Second Value"))

Select Case UserInput

Case 1
aaamsgbox"The Sumation of "&Var1& " and " &var2& " is: "&Var1 + Var2
Case 2
aaamsgbox"The difference between "&Var1& " and " &var2& " is: "&Var1 - Var2
Case 3
aaamsgbox"The product of "&Var1& " and " &var2& " is: "&Var1 * Var2
Case 4
aaamsgbox"The quotient between "&Var1& " and " &var2& " is: "&Var1 \ Var2
Case Else
aaamsgbox "Invalid entry"
End Select


Previous11121314151617181920Next

Answers to Assignments for If Else Statement

Please find the answer to the assignment on If Else statements.

1. Write a script to print the greatest of three integers.


Look at the script below.

Var1 = CINT(Inputbox("Enter value for Var1: "))
Var2 = CINT(Inputbox("Enter value for Var2: "))
Var3 = CINT(Inputbox("Enter value for Var3: "))

if Var1=Var2 and Var1=Var3 then
aaaamsgbox"All the values are same: "&Var1
elseif Var1=Var2 and Var1>Var3 then
aaaamsgbox"Var1 & Var2 i.e. " &Var1& " is greater than "&Var3
elseif Var1=Var3 and Var1>Var2 then
aaaamsgbox"Var1 & Var3 i.e. " &Var1& " is greater than "&Var2
elseif Var2=Var3 and Var2>Var1 then
aaaamsgbox "Var2 & Var3 i.e. " &Var2& " is greater than "&Var1
elseif Var1>Var2 and Var1>Var3 then
aaaamsgbox "Var1 i.e. "&Var1& " is greater than "&Var2& ", "&Var3
elseif Var2>Var1 and Var2>Var3 then
aaaamsgbox "Var2 i.e. "&Var2& " is greater than "&Var1& ", "&Var3
else
aaaamsgbox "Var3 i.e. "&Var3& " is greater than "&Var1& ", "&Var2
end if

In the above script we are joining the values and some meaning ful string to the message and this is done using the '&' which is to join the strings.

2. Write a script to print the least of the three integers.

For this please think and write. you have to only make some small change.

Back to If Else Statement page

VB Scripting - Else If Statement

Previous11121314151617181920Next


The If Else statement we discussed previously executes one block of code if the value is greater than 80 or executes the other piece of code if the condition is not satisfied. Now think what you will do if you have different ranges.

To do this you need Else If statement.



What Else if does is that it creates and if statement within an if statement and goes on and in this manner you can check different conditions in a single if Statement.

Syntax for Else If Statement



If [condition] Then
Code
Elseif [condition] Then
Code
Elseif [condition] Then
Code
Elseif [condition] Then
Code
Else
Code
End If


Example to show how Else If Statement is used


Now let write a script to see how this works. We will calculate the average for three subjects and based on the percentage we will display the average and the appropriate messages.


'Calculating the average for three subjects
mt = Inputbox("Enter the marks scored for Manual Testing:")
qtp = Inputbox("Enter the marks scored for QTP:")
sql = Inputbox("Enter the marks scored for SQL:")
'Calculating average
avg=(mt+qtp+sql)/3
'Displaying the average to the user
msgbox "The average marks scored is: "&avg
'Branching statements to display appropriate message
If avg >= 90 Then
msgbox "You scored "&avg&" percentage and you will get a Job"
ElseIf avg >= 80 and avg < 90 Then
msgbox "You scored "&avg&" percentage and you have to put in more effort"
ElseIf avg >= 70 and avg < 80 Then
msgbox "You scored "&avg&" percentage and you are not up to the mark"
Else
msgbox "You scored "&avg&" percentage and you have to repeat the course"
End If



What happened why did this result came as 100.333333333333 and the first message will be displayed which is wrong.

Let’s debug the script line by line.

mt=3, qtp=0, sql=1
avg=(mt+qtp+sql)/3
avg=(3+0+1)/3
avg 301/3
avg=100.333333333333


Let me explain you what happened so that we will be clear as to what happened and how to rectify the code.

Even though we say that in the condition avg=(mt+qtp+sql)/3 we have used addition (+) operator but just to remind that the default type of Inputbox is string because we have not explicitly declared the variables and that’s why by default what ever values you have entered in the input box is taken as string and in context of this + is treated as a concatenation operator which means that it will join the three values as 3+0+1 to make 301 and not add them up to 4. That is the reason we are getting a different result.

In order to rectify this issue we need to use a conversion type (Type Cast) which in our case actually converts the default data type to integer type. For this we need to use CINT. CINT can be used with input box or while on the expression calculating the average (In our case). You cannot use CINT for some variables while accepting values and for some on the expression. You can either use CINT on the expression or while taking input on variables.


Let’s rewrite the code and see what happens

'Calculating the average for three subjects
mt = CINT(Inputbox("Enter the marks scored for Manual Testing:"))
qtp = CINT(Inputbox("Enter the marks scored for QTP:"))
sql = CINT(Inputbox("Enter the marks scored for SQL:"))
'Calculating average
avg=(mt+qtp+sql)/3
'Displaying the average to the user
msgbox "The average marks scored is: "&avg
'Branching statements to display appropriate message
If avg >= 90 Then
msgbox "You scored "&avg&" percentage and you will get a Job"
ElseIf avg >= 80 and avg < 90 Then
msgbox "You scored "&avg&" percentage and you have to put in more effort"
ElseIf avg >= 70 and avg < 80 Then
msgbox "You scored "&avg&" percentage and you are not up to the mark"
Else
msgbox "You scored "&avg&" percentage and you have to repeat the course"
End If




Now run the script and you will get the right percentage and the required message.

Note: You can also use CINT on the expression instead on inputbox. It will look like this.
(CINT(mt)+CINT(qtp)+CINT(sql))\3

Assignments on Else If Statement

1. Write a script to print the greatest of three integers.
2. Write a script to print the least of the three integers.

Click Here for answers for Assignments


Previous11121314151617181920Next

VB Scripting - If Statement

Previous11121314151617181920Next


If Else statement in VB script is used when you want to execute a block of code based on certain condition.


Syntax for If Else Statement


If [Condition] Then
AAAACode
AAAACode
Else
AAAACode
AAAACode
End If


Example to show how If Else Statement is Used


We will write a script asking the user to enter the average scored and based conditions given appropriate message is displayed.

'Code to demonstrate If Else condition
Varint1 = Inputbox("Enter the average score you gained:")
If Varint1 > 80 Then
AAAAmsgbox "You scored " &Varint1& " percentage and are the winner"
Else
AAAAmsgbox "You scored " &Varint1& " percentage and do not qualify."
End If


If the user enters 85 then the output displayed will be

You Scored 85 percentage and are the winner


If user enters any thing less than 80 say 75 the output displayed will be

You Scored 85 percentage and do not qualify.


Previous11121314151617181920Next

VB Scripting - Branching Statements

Previous11121314151617181920Next

What is Branching and types of Branching Statements?


Branching Statements in VB Scripting provides a user with a choice to execute certain piece of code based on the condition. This would help us to validate different conditions for one expression.


In general to say that the program or code has to make a decision based on a condition when a user gives a input or based on some parameters or values the decision has to be made then branching statements plays a vital role.

For example take this scenario of giving different grades to a student based on the percentage. For one student you can assign the marks to different variables and based on the average you can branch out your code and give the grade but imagine if you have to run it for more that one student then manually you have to go into the code and change for every student and save and run.

Branching Statements helps you in making the code decide the grade based on the conditions you give in the code once and ask the user to enter the marks for each student. Using these branching statements you can branch out your code to different conditions.

Basically there are three types of Branching Statements

1. If Else
2. If Elseif
3. Switch Case


Out of these the popular branching or conditional statement used is the If Else, Endif

Else and Elseif are used to branch out different conditions.

Previous11121314151617181920Next

Monday, April 12, 2010

VB Scripting - Operators

Previous12345678910Next

What is the need for Operators?


Operators in VB Script are to used to perform some operations or do some manipulation on variables or values. Operator is a notation to perform operation and this operation will happen on one or more operands.


Operators in VB script can be classified in to mainly four. They are

  • Arithmetic Operators.
  • Logical Operators.
  • Relational or Comparison Operators.
  • Concatenation Operator.

  • VB Script – Arithmetic Operators


    Arithmetic operators are used for arithmetic operations or mathematical operations such as Addition, Subtraction, Multiplication and other kinds of operations.
    Please find the list of Operators with some examples for easy understanding.

    Operator English MeaningExample Result
    + Add 5+27
    - Subtract 5-23
    * Multiply 5*210
    / Floating Point Division 5/22.5
    \Integer Division5\22
    ^ Exponent 5^225
    Mod Modulus 5 Mod 2 1

    Logical Operators


    Logical operators are used to perform logical operations. They are used to manipulate statements or create logical expressions. The Logical operators are AND, OR and NOT.
    Please find the list of Operators with some examples for easy understanding.

    Operator English MeaningExample Result
    Not Inverts Value Not False True
    Or Either Can Be True True or False True
    And Both Must Be True True And False False

    Relational or Comparison Operators


    Relational operators are also called as comparative operators like if we want to compare numbers etc. Generally they are used in conditional statements like IF Else or While loops.
    Please find the list of Operators with some examples for easy understanding.

    Operator English MeaningExample Result
    = Equal To 20 = 45False
    > Greater Than 20 > 45 False
    < Less Than 20 <>True
    >= Greater Than or Equal To 20 >= 45False
    <= Less Than or Equal To 20 <= 45 True
    <>Not Equal To 20 <> 45 True

    Concatenation Operator


    In order to combine two strings and display as a single string we use Concatenation Operator (&). We use “&” to join two expressions.
    Please find below the description with examples for easy understanding.

    Operator English MeaningExample Result
    &Join or Connect"Hello" & "World"Hello World


    Previous12345678910Next

VB Scripting - Data Types

Previous12345678910Next

What are the Data Types in VB Script?


Data types in VB Script is used in context of Variable. There is only one data type in VB Script called as Variant. The specialty of a Variant is that it can hold different forms of data or information within the variable and there is no need to explicitly define the type of data.


A Variant can hold data which contains either a numeric or a string value. The Variant behaves in the way you want i.e. behaves as a numeric value when used in a numeric context and behaves like a string when used in a string context. The only difference is that any data which is enclosed in quotation marks (" ") behaves like a string even though it contains only numbers.

Variant Subtypes


Variant can hold any type of data like Integer, String, Long, Single or double etc. The different categories of information/data which a Variant can hold are called as subtypes.

Below table gives a clear picture of subtypes of data which a Variant can hold or contain.
SubtypeDescription
IntegerThe size is of 2 bytes, Value can be from 0 to 255, The Integer range is from -32,768 to 32,767.
Long Long is for numbering system, The Integer range is from -2,147,483,648 to 2,147,483,647.
SingleHolds small precision, floating point range is from -3.402823E38 to -1.401298E-45 for negative values and for positive values is from 1.401298E-45 to 3.402823E38.
DoubleHolds big precision, floating point range is from -1.79769313486232E308 to -4.94065645841247E-324 for negative values and for positive values is from 4.94065645841247E-324 to 1.79769313486232E308.
CurrencyRanges from -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Date (Time)The range is between January 1, 100 to December 31, 9999.
ObjectContains an object.
BooleanContains a boolean value either True or False.
EmptyVariant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.
NullVariant intentionally contains no valid data.
ByteContains integer in the range 0 to 255.


You can use the conversion functions to convert the data from one subtype to another subtype which will be discussed in Type Cast lesson.

Previous12345678910Next

VB Script - Variable - Explicit Declaration

Previous12345678910Next

Explicit Declaration


Explicit Declaration is used to avoid the unnecessary confusion created while typing and also to avoid loading the memory with variables because of errors we can use Explicit Declaration. In order to use explicit declaration type we need to declare the variables before the script begins or it should be in the starting of the script.


We will use the same example used for Implicit Declaration but will change the script. In order to create Explicit Declaration in the beginning of the code we need to add one more line of code as ‘Option Explicit”. Take a look at the code for Explicit Declaration

Option Explicit
Dim Int1, Int2, Prod
Int1 = 28
Int2 = 30
Prod = Int1 * Int2
Msgbox Prod

Now lets debug the code. If by mistake instead of “Prod” you type “Prd” in Line 6 as Msgbox Prd then what will happen. Since “Prd” is not declared when you run the script it executes the first five line and when it executes the sixth line it throws error and till it is not rectified the resultant output is not displayed. It will throw error as “Variable is undefined: ‘Prd’.

This is the advantage of using Explicit Declaration.

Previous12345678910Next