10
Q11. Define datatype. What are the different data types available in VB? In Visual Basic, we have to deal with many sorts of data, some can be mathematically calculated while some are in the form of text or other forms. VB divides data into different types so that it is easier to manage when we need to write the code involving those data. Visual Basic classifies data into two major types, they are the numeric data types and the non-numeric data types. Numeric Data Types Numeric data types are types of data that consist of numbers, which can be computed mathematically with various standard operators such as add, minus, multiply, divide and more. In Visual Basic, numeric data are divided into 7 types, depending on the range of values they can store. Numeric Data Types Type Storage Range of Values Byte-----------1 byte--------------------0 to 255 Integer-------2 bytes--- -32,768 to 32,767 Long ---------4 bytes -2,147,483,648 to 2,147,483,647 Single--------4 bytes Double------8 bytes Currency---8 bytes Decimal----12 bytes Non-numeric Data Types Nonnumeric data types are data that cannot be manipulated mathematically using standard arithmetic operators. The non-numeric data comprises text or string data types, the Date data types, the Boolean data types that store only two values (true or false), Object data type and Variant data type . Nonnumeric Data Types Data Type Storage Range String(fixed length)------Length of string------1 to 65,400 characters String(variable length)--Length + 10 bytes----0 to 2 billion characters Date-------------------------8 bytes --------------January 1, 100 to December 31, 9999 Boolean--------------------2 bytes-------------True or False Object----------------------4 bytes ------------Any embedded object Variant(numeric)------16 bytes ------------Any value as large as Double Variant(text)------------Length+22 bytes--Same as variable-length string Q11(a) Describe data type conversion in VB6.

VB-11-20

Embed Size (px)

DESCRIPTION

Visual Basic

Citation preview

Page 1: VB-11-20

Q11. Define datatype. What are the different data types available in VB? In Visual Basic, we have to deal with many sorts of data, some can be mathematically calculated while some are in the form of text or other forms. VB divides data into different types so that it is easier to manage when we need to write the code involving those data.Visual Basic classifies data into two major types, they are the numeric data types and the non-numeric data types.Numeric Data TypesNumeric data types are types of data that consist of numbers, which can be computed mathematically with various standard operators such as add, minus, multiply, divide and more. In Visual Basic, numeric data are divided into 7 types, depending on the range of values they can store.Numeric Data TypesType Storage Range of ValuesByte-----------1 byte--------------------0 to 255Integer-------2 bytes--- -32,768 to 32,767Long ---------4 bytes -2,147,483,648 to 2,147,483,647Single--------4 bytesDouble------8 bytesCurrency---8 bytesDecimal----12 bytesNon-numeric Data Types Nonnumeric data types are data that cannot be manipulated mathematically using standard arithmetic operators. The non-numeric data comprises text or string data types, the Date data types, the Boolean data types that store only two values (true or false), Object data type and Variant data type . Nonnumeric Data Types Data Type Storage RangeString(fixed length)------Length of string------1 to 65,400 charactersString(variable length)--Length + 10 bytes----0 to 2 billion charactersDate-------------------------8 bytes --------------January 1, 100 to December 31, 9999Boolean--------------------2 bytes-------------True or FalseObject----------------------4 bytes ------------Any embedded objectVariant(numeric)------16 bytes ------------Any value as large as DoubleVariant(text)------------Length+22 bytes--Same as variable-length stringQ11(a) Describe data type conversion in VB6.

In Visual Basic, data types can be converted from one data type to another. Some data type conversion functions are given below.Function Description Asc() Converts its string argument to the ASCII number that matches the first (or only)

character in the stringCCur() Converts the argument to an equivalent Currency datatypeCDbl() Converts the argument to an equivalent Double datatypeCInt() Rounds its fractional argument to the next highest integerCLng() Converts the argument to an equivalent Long datatypeCSng() Converts the argument to an equivalent Single datatypeCStr() Converts the argument to an equivalent String datatypeCVar() Converts the argument to an equivalent Variant datatypeFix() Truncates the fractional portionInt() Rounds the number down to the integer less than or equal to its argumentsHex() Converts its numeric argument to a hexadecimal (base-16) valueOct() Converts its numeric argument to an octal (base-8) value

Hexadecimal is the base-16 number system. Octal is the base-8 number system.

Page 2: VB-11-20

Normally, the following assignment stores .1428571 in a label named lblValue:

lblValue.Caption = (1 / 7)

The following, however, adds precision to the label for a more accurate calculation to assign .142857142857143 to the label:

lblValue.Caption = CDbl(1 / 7)

Use these conversion functions when you need the exact datatype for more precision in calculations or controls.

Q12. What are type declaration character?

A Type Declaration Character is a character appended to a variable name indicating the variable's data type. For example, the variable name MyString$ has a dollar sign appended to the variable name and is dimensioned as a String data type.The following shows the type declaration characters and corresponding data types. Type Declaration Character Data Type % Integer & Long ! Single # Double $ String @ Currency Even when using type declaration characters, variables declaration is still required when we have Option Explicit at the beginning of the Module. Using Option Explicit is recommended to prevent problems due to misspelled variable names.

Q13. Explain order of precedence of operators for calculations?Ans:1. The order in which operator are performed determines the result. Consider the expressions 3 + 4 * 2. Over here if addition is done first, the result is 14. However, if multiplication is done first then result is 11.2. The hierarchy of operations, or order of operations, or order of precedence, in arithmetic expressions from highest to lowest is:a. Exponentiationb. Multiplication and Divisionc. Addition and Subtraction3. In the previous example, the multiplication is done before addition, and the result is 11. to change the order of evolution, use parenthesis:(3 + 4) * 2will yield 14 as the result. One set of parenthesis can be used inside another set. In the case, parenthesis are said to be nested.

Q14. Explain in detail about the various function used for formatting the data ? Ans.When you want to formate data for display , either on the printer or on the screen , use the formatting function.To format means to control the way the output will look.Example :12 is just a number but $12.00 conveys more meaning for dollar amount. VB 6.0 introduces four new formatting function:

Page 3: VB-11-20

i. The FormatCurrency Function : The FormatCurrency function returns a string of character formated as dollar and cents by default , The currency value display a dollar sign and comma and two postion to the right of the decimal point.Example:lblBalance.Caption = FormatCurrency ( Balance )value1275.675.5FunctionFormatCurrency ( curBalance )FormatCurrency ( sngAmount )Output$1,275.68$0.50ii. The FormatNumber Function : The FormatNumber function is similar to the FormatCurrency function. The default format is determine by your computer aegional setting. It will generally display commas and two digit to the right of the decimal point.Syntax:FormatNumber ( Expression-To-Format )Example:lblSum.Caption = FormatNumber ( Sum )Value1125.671234.567FuntionFormatNumber ( mcurTotal , 0 )FormatNumber ( curBalance , 2 )Output1,1261,234.57iii.The FormatPercent Function : To display numeric values as a percent ,use the FormatPercent( ) . This function multiplies the argument by 100 , adds a percent sign, and rounds to the decimal places.Syntax :FormatPercent ( ExpressionToFormat [ , NamedFormat ] )Example :lblInterest.Caption = FormatPercent ( Rate )In the complete form of the FormatPercent function. You can select the number of digit to the right of the decimal point .Value.75.75FunctionFormatPercent ( curCorrect )FormatPercent ( curCorrect , 1 )Output75%75.0%iv. The FormatDateTime Function :You can format an expression as a date or a time . The Expression maybe a string that holds a date or time value , a date type varible or a function that return a date.If you omit the optional named format, the function returns the date usingvbGeneralDate.Named Format

Page 4: VB-11-20

ExampleReturnsvbGeneralDatedate. If it holds a time, A date and/or time. If the expression holds a date, returns a short2/28/99 6:01returns a long time. If it holds both , returns both a short date and longvbLongDateSunday,February 28,1999Day of week , Month Day , YearMM/DD/YYHH:MM:SS AM/PMHH:MM( 24 hour clock )Example:lblStartDate.Caption = FormatDateTime ( StartDate , vbShortDate )lblStartTime.Caption = FormatDateTime ( "1/1/07" ,vbLongDate )

Q14(a). What do you mean by implicit and explicit variable declaration?

In Visual Basic, one needs to declare the variables before using them by assigning names and data types. They are normally declared in the general section of the codes' windows using the Dim statement. There are two principle ways to add variables in VB applications.

The first method – called implicit declaration –Visual Basic automatically create the variable when it encounters a new variable and it assigns the default variable type i.e. variant and value. This is called implicit declaration.. The second is explicit declaration: Though implicit type of declaration is easier for the user, to have more control over the variables, it is advisable to declare them explicitly. The Option Explicit statement checks in the module for usage of any undeclared variables and reports an error to the user. The user can thus rectify the error on seeing this error message. The syntax for explicitly declaring a variable is quite simple:

Dim VariableName As DataTypeStatic VariableName As DataTypePrivate VariableName As DataTypePublic VariableName As DataType

Q15. What do you understand by scope and lifetime of a variable

Depending on the keyword used to declare the variable and the placement of the variable’s declaration in the program’s code, the variable might be visible to large portions of the application’s code. Alternatively, a different placement might severely limit where the variable can be referenced in the procedures within the application.

The visibility of a variable or procedure is called its scope. Depending on the scope of the variable, it can be categorised into three types.

(1) Private or local scope: The variable that is usable by a single procedure, is said to have private scope to that procedure. Variables declared within a procedure are local to that procedure and cannot be used or referenced outside that procedure and has private scope.

(2) Public scope: A variable that can be seen and used by any procedure in the application is said to have public scope.

Page 5: VB-11-20

(3) Module scope: The variable which is accessible to all procedures in the module in which it is declared is said to have module scope.

Variables have a lifetime in addition to scope. The values in a module-level and public variables are preserved for the lifetime of an application whereas local variables declared with Dim exist only while the procedure in which they are declared is still being executed. The value of a local variable can be preserved using the Static keyword.

Q16. What is static variable?

Static Variable: - A variable with local scope and whose value does not change under any procedure or function call is known as static variable.Static variable is described as:Static a Usefulness:-• The lifetime of the variable changes so that the variables lives on in the memory even after its parent procedure is over.• A static variable is not removed from memory even after its procedure is over. Thus, it retains its value.• And next time its procedure gets executed, the static variable’s old value is accessible.• However, the scope of a static local variable remains unchanged i.e., it remains private to the procedure.• Advantage of using such variable is that they help you minimize the number of variables in the application.

Q17. How is a static variable different from other variable.When a variable is declared with Procedure level scope it only exists while the code in the corresponding procedure is executing. Once the procedure completes, the variable and the variable assigned to it are destroyed. Under certain circumstance it may be necessary for the variable and the current value assign to it to persist beyond the life of the procedure. Next time the procedure is called, therefore, the variable still holds the value it held on the previous invocation of the procedure. The syntax to declare a static variable is as follows:Static variableName As dataTypeQ18. What is purpose of the Val function?Ans:1. Visual Basic provides number of built in functions. The Val function is one of it. Val function converts the text data into a numeric value.The general form of Val function is as follows:Val(Expression to Convert)2. The expression you wish to convert can be the property of control, a variable, or a constant.3. A function cannot stand by itself. It returns (produces) a value that can be used a part of a statement, such as the assignment statements in the following examples.4. When the Val function converts as argument to numeric, it begins at argument’s left most character. If that character is a number digit, decimal point, or sign, Val converts the character to numeric and moves to the next character. As soon as a nonnumeric character is found, the operation stops.5. Example: Val(123.45) will return = 123.45 and Val(123A5) will return 123 only.

Q19. What is difference between Dim and Redim statements?Dim statement is used to formally declare a variable, whereas ReDim statement is used to resize a dynamic array that has already been formally declared.You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array.

Page 6: VB-11-20

For example you have declared an array Dim Customers(50)But now you want to change the size of the array so you can do that with the help of Redim. ReDim Customers(100)Q19(a) What do you mean by control statement and decision statement.VB provides statements that can alter the flow of a sequence of instructions. These statements are called control statements. These statements help to jump from one part of the program to another. The control transfer may be conditional or unconditional. These statements are called as control statements.The control transfer may be unconditional or conditional. Branching Statement are of following categories:

If Statement The If else Statement Compound Relational tests Nested if Statement Switch StatementThe basic decision statement in VB is the If……End If statement. Which executes the decision between the If and End If keywords if the conditions specified in the If part is true.Q19(b) Explain how Select Case work with an appropriate example. Select Case is preferred when there exist many different conditions because using If...Then..ElseIf statements might become too messy.

The format of the Select Case control structure is show below:

Select Case expression

Case value1 Block of one or more VB statements Case value2 Block of one or more VB Statements Case value3 . . Case Else Block of one or more VB Statements End SelectExample:

Dim grade As String Private Sub Compute_Click( ) grade=txtgrade.Text Select Case grade   Case  "A"        result.Caption="High  Distinction"   Case "A-"       result.Caption="Distinction"   Case "B"         result.Caption="Credit"   Case "C"         result.Caption="Pass"   Case Else         result.Caption="Fail"   End Select End Sub

Page 7: VB-11-20

Q19(c) Explain Do Until loop and Do While loop with appropriate examples and also give their difference.

In Do Until loop , the loop continues as long as the expression is false.Example:Dim intTotal as integerDo Until intTotal > 10 intTotal = intTotal + 1 MessageBox.Show("intTotal = " + CStr(intTotal))LoopIn Do While loop, the loop continues as long as the expression is true.Example:

Dim intTotal as integerDo While intTotal < 10 intTotal = intTotal + 1 MessageBox.Show("intTotal = " + CStr(intTotal))Loop

Sl.No Do While loop Do Until loop

1. The Do-While loop causes the loop to continue until an expression ceases to evaluate to True.

A 'Do-Until' loop causes the loop to continue until a condition is no longer true.

2. The Do While's condition appears at the top of the loop. Therefore, if condition is false the first time the loop begins, the body of the loop will never execute.

This loop has a condition at the end. Since the check is at the end, the statements are at least executed once.

Q19(d). What is enumeration loop? Show the use of it with an example.

Enumerations provide a convenient way to work with sets of related constants, and to associate constant values with names. To iterate through an enumeration, you can move it into an array using the GetValues method. To iterate through an enumeration

Declare an array and convert the enumeration to it with the GetValues method before passing the array as you would any other variable. The following example displays each member of the enumeration FirstDayOfWeek as it iterates through the enumeration.

Dim items As Arrayitems = System.Enum.GetValues(GetType(FirstDayOfWeek))Dim item As StringFor Each item In items MsgBox(item)Next

Q20. What are the purpose of a Declare Statement?

Ans.Declaring variables means naming the variable and specifying their data types, that is declaration statements establish our project’s variables and constants give them names, and specify the data type they will hold. These declaration statements are not considered as

Page 8: VB-11-20

executable ; that is, they are not executed in flow of instructions during program execution. Although these are several ways of declaring the variables, the most commonly used way is the Dim statements with the data type. We can omit the data type, then default data type becomes variant.Here are some sample examples for declaration statement :Dim strName as String ‘Declared the String variableDim intCount as Integer ‘Declared an Integer variableDim curDiscount as Currency ‘Declared a currency variable