VB FUNCTIONS AND OPERATORS

Similar documents
Programming Language 2 (PL2)

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Chapter 2: Using Data

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

Microsoft Visual Basic 2005: Reloaded

Full file at

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Visual C# Instructor s Manual Table of Contents

ECE 122 Engineering Problem Solving with Java

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Operators and Expressions

Microsoft Visual Basic 2015: Reloaded

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Arithmetic Expressions in C

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Programming in C++ 6. Floating point data types

Chapter 2: Data and Expressions

Chapter 2: Using Data

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Outline. Data and Operations. Data Types. Integral Types

SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS

Number Representation & Conversion

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Values, Variables, Types & Arithmetic Expressions. Agenda

MODULE 02: BASIC COMPUTATION IN JAVA

Introduction to Programming Using Java (98-388)

Chapter 2: Data and Expressions

Java Primer 1: Types, Classes and Operators

Information Science 1

Chapter 2: Using Data

Lab 3 The High-Low Game

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Chapter 02: Using Data

Unit 3. Operators. School of Science and Technology INTRODUCTION

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Programming Using C Homework 4

Full file at

Murach s Visual Basic 2012, C4 2013, Mike Murach & Associates, Inc. Slide 1. The built-in value types (continued)

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Copyright 2014 Pearson Education, Inc. Chapter 3. Variables and Calculations. Copyright 2014 Pearson Education, Inc.

More Programming Constructs -- Introduction

Zheng-Liang Lu Java Programming 45 / 79

Type Conversion. and. Statements

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Information Science 1

Data and Operations. Outline

3.1. Chapter. CSC 252 (MIS 385) Chapter 3 Input, Variables, Exceptions, and Calculations. Introduction. Page 1

Programming Lecture 3

Informatics Ingeniería en Electrónica y Automática Industrial

Topic 2: Introduction to Programming

Learning the Language - V

1.3b Type Conversion

Reserved Words and Identifiers

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Primitive Data Types: Intro

Data Types. Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

COMP 110 Introduction to Programming. What did we discuss?

C++ Programming: From Problem Analysis to Program Design, Third Edition

UNIT- 3 Introduction to C++

4. Inputting data or messages to a function is called passing data to the function.

Visual Basic distinguishes between a number of fundamental data types. Of these, the ones we will use most commonly are:

Program Fundamentals

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Homework #3 CS2255 Fall 2012

LECTURE 3 C++ Basics Part 2

Vba Variables Constant and Data types in Excel

2.Simplification & Approximation

CIS 110: Introduction to Computer Programming

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Types and Expressions. Chapter 3

Ex: If you use a program to record sales, you will want to remember data:

Chapter 2 Elementary Programming

Computer System and programming in C

ARG! Language Reference Manual

CIS133J. Working with Numbers in Java

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

3. Java - Language Constructs I

Object Oriented Programming with Visual Basic.Net

CHAPTER 3 Expressions, Functions, Output

Prof. Navrati Saxena TA: Rochak Sachan

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Arithmetic Operations

Operators. Java operators are classified into three categories:

Chapter 2: Data and Expressions

VBScript: Math Functions

Lecture 1. Types, Expressions, & Variables

Transcription:

VB FUNCTIONS AND OPERATORS In der to compute inputs from users and generate results, we need to use various mathematical operats. In Visual Basic, other than the addition (+) and subtraction (-), the symbols f the operats are different from nmal mathematical operats, as shown in the table below: OPERATOR MATHEMATICAL FUNCTION EXAMPLE ^ Exponents 2 ^ 4 = 16 * Multiplication 4 * 3 = 12 / Division 12 / 4 = 3 + Addition 7 + 5 = 12 - Subtraction 7 5 = 2 Mod Modulus (returns the remainder from an integer division) 15 Mod 4 = 3 \ Integer Division (discards the decimal places) 19 \ 4 = 4 + & String concatenation ICS & 2O1 = ICS2O1 ORDER OF OPERATIONS Visual Basic evaluates a numeric expression using a specific der of operations, operat precedence. The following table outlines the der of operations used in Visual Basic: ORDER OPERATOR FUNCTION 1 st ^ Exponents 2 nd +, - Unary 3 rd *, / Multiplication and Division 4 th \ Integer Division 5 th Mod Modulus 6 th +, - Addition and Subtraction VB Functions and Operats Page 1 of 11

Operat precedence can, of course, be changed by including parentheses in a numeric expression. The operations within parentheses are evaluated first. COMBINED ASSIGNMENT OPERATORS Sometimes you might find it necessary to change the value of a variable by doubling it subtracting a certain amount from it while keeping the result in the variable itself. Combined assignment operats (sometimes called compound operats) are designed to do just that. Without compound operats, you would have to type the variable name twice once f the left ption of the equation and again in the right ption of the equation. The following table outlines the compound operats available in Visual Basic: COMPOUND OPERATOR EXAMPLE EQUIVALENT += x += 5 x = x + 5 -= x -= 5 x = x - 5 *= x *= 5 x = x * 5 /= x /= 5 x = x / 5 \= x \= 5 x = x \ 5 &= name &= lastname name = name & lastname VB Functions and Operats Page 2 of 11

IMPLICIT TYPE CONVERSION When you assign a value to one date 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. This is known as implicit type conversion. F example, let s say we want to assign the integer 5 to a variable of type Single named num: Dim num As Single = 5 When the statement executes, the integer 5 is automatically converted into the real number 5.0, which is then sted in the variable num. This conversion is what s called a widening conversion because no data is lost. NARROWING CONVERSIONS If you assign a real number to an integer variable, Visual Basic attempts to perfm what s called a narrowing conversion. Oftentimes, some data is lost. F example, the following statement assigns 12.2 to an integer variable: Dim num As Integer = 12.2 The value 12.2 is rounded down to 12. Similarly, the next statement rounds up to the nearest integer (i.e. 13) when the fractional part of the number is greater than.5: Dim num As Integer = 12.6 Another narrowing conversion occurs when assigning a Double value to a variable type Single. Both hold floating-point values, but Double permits me significant digits: Dim numone As Double = 1.2345678 Dim numtwo As Single = numone The value sted in numtwo is rounded up to 1.234568 because variables of Single type can only hold seven significant digits. CONVERTING STRINGS TO NUMBERS Under some circumstances, Visual Basic will try to convert string values to numbers. In the following statement, f example, 12.2 is a string containing a numeric expression: Dim num As String = 12.2 VB Functions and Operats Page 3 of 11

The string 12.2 is a string of characters in a numeric-like fmat that cannot be used f calculations. When the following statements execute, the string 12.2 is converted to the number 12.2: Dim num As Single num = 12.2 If we assign the string 12.2 to an Integer variable, the result is rounded down to 12: Dim num As Integer num = 12.2 A similar effect occurs when the user enters a number into a TextBox control. We usually want to assign the contents of the text box s Text property to a numeric value. The Text property is by definition type String, so its contents are implicitly converted to a number when we assign it to a numeric variable: Dim num As Integer num = txtvalue.text OPTION STRICT Visual Basic has a configuration option named Option Strict that determines whether certain implicit conversions are legal. If you set Option Strict to ON, only widening conversions are permitted (such as Integer to Single). The following diagram shows how implicit conversion between numeric types must be in a left-to-right direction: Byte Integer Long Decimal Single Double A Single value can be assigned to a variable of type Double, an Integer can be assigned to a variable of type Single, etc. If, on the other hand, Option Strict is set to OFF, all types of numeric conversions are permitted, with possible loss of data. Option Strict can be set in two different ways: 1. By inserting an Option Strict statement at the top of the source code file: Option Strict On 2. Right-click the project name in the Solution Expler window, select Properties, and then select the Compile tab. From the Option Strict drop-down list, you can select ON OFF. VB Functions and Operats Page 4 of 11

Click COMPILE Click ON OFF It is recommended that you use Option Strict to catch errs that result when you accidentally assign a value of the wrong type to a variable. When set to ON, Option Strict fces you to use a conversion function, making your intentions clear, and helps to avoid runtime errs. EXPLICIT TYPE CONVERSIONS The following table outlines the most commonly used Visual Basic conversion functions. The input to each of the conversion functions is an expression, which is another name f a variable name, an arithmetic expression, etc. These conversion functions are required when Option Strict is set to ON and you need to assign a wider numeric type to a narrower numeric type (e.g. Long to Integer, Double to Single, etc.) FUNCTION CChar(expr) Convert.ToChar(expr) CBool(expr) Convert.ToBoolean(expr) CDbl(expr) Convert.ToDouble(expr) CInt(expr) Convert.ToInt32(expr) CLng(expr) Convert.ToInt64(expr) DESCRIPTION Converts a string expression to a Char. If the string contains me than one character, only the first character is returned. Converts a string expression (that must equal True False) to a Boolean. If the expression does not equal True, False Nothing, a runtime err is generated. Converts a numeric string expression to a Double. If the expression converts to a value outside the range of a Double, is not a numeric value, a runtime err is generated. Converts a numeric string expression to an Integer. If the expression converts to a value outside the range of an Integer, is not a numeric value, a runtime err is generated. Converts a numeric string expression to a Long. If the expression converts to a value outside the range of a Long, is not a numeric value, a runtime err is generated. CSng(expr) Converts a numeric string expression to a Single. VB Functions and Operats Page 5 of 11

Convert.ToSingle(expr) CStr(expr) Convert.ToString(expr) If the expression converts to a value outside the range of a Single, is not a numeric value, a runtime err is generated. Converts a numeric, Boolean, Date String expression to a String. THE ToString() METHOD Each Visual Basic data type has a ToString() method, which returns a string representation of the variable calling the method. You call the ToString() method using the following general fmat: VariableName.ToString() The following code segment shows an example of the method s use: Dim num As Integer = 123 lblnumber.text = num.tostring() VB Functions and Operats Page 6 of 11

Numbers may be fmatted in various ways f output. Visual Basic provides a number of fmatting functions that allow you to convert values to strings and fmat their appearances. THE FmatNumber FUNCTION By default the FmatNumber function fmats a number to two decimal places and includes commas. F example, the number 1999 would be fmatted as 1,999.00. The number 123456789.89712 would be fmatted as 123,456,789.90. The following code is an example of how the FmatNumber function is used: Dim num As Double num = 7823.279 lblmessage.text = FmatNumber(num) The last statement passes the variable num to the FmatNumber function and returns the string 7,823.28, which is assigned to the lblmessage.text property. The FmatNumber function takes an optional second argument, which specifies the number of decimal places. The following example fmats a variable called laptime to four (4) decimal places: lblmessage.text = FmatNumber(lapTime, 4) THE FmatCurrency FUNCTION The FmatCurrency function fmats a number as currency (e.g. $5.85). The number is rounded to two (2) decimal places and includes commas as needed. The following is an example of how the FmatCurrency function is used: Dim totalcost As Double totalcost = 45123.9823 lbltotal.text = FmatCurrency(totalCost) The last statement passes the variable totalcost to the FmatCurrency function and returns the string $45,123.98, which is assigned to the lbltotal.text property. THE FmatPercent FUNCTION The FmatPercent function fmats a number as a percent by multiplying the argument by 100, rounding the result to two decimal places, and adding a percent symbol. The following is an example of how the FmatPercent function is used: VB Functions and Operats Page 7 of 11

Dim average As Double average = 0.56789 lblaverage.text = FmatPercent(average) The last statement passes the variable average to the FmatPercent function and returns the string 56.79%, which is assigned to the lblaverage.text property. Like FmatNumber and FmatCurrency, the FmatPercent function takes an optional second argument, which specifies the number of decimal places. The following example fmats the variable called average to zero (0) decimal places: lblaverage.text = FmatPercent(average, 0) VB Functions and Operats Page 8 of 11

Games, simulats, screen savers, and many other types of applications require random numbers. Visual Basic includes a Random class that generates a random number. In der to use the Random class, the first thing you need to do is create a new Random object as follows: 'Declare and initialize Random object Dim rnd As New Random The next thing you ll need to do is declare a variable that will ste the number that is randomly generated by the Random object that we created above: 'Declare and initialize variable to ste random number Dim randomnumber As Integer To generate a random number, we will need to use the Next() method included in the Random class which generates a positive integer value greater than equal to zero and less than 2,147,483,647. 'Generate and ste random number randomnumber = rnd.next() Let s now add a user interface to see how this program would wk. Create a fm and add a label and button as follows: lblnumber btngenerate Add the following code to the button: Private Sub btngenerate_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles btngenerate.click 'Declare and initialize Random object Dim rnd As New Random 'Declare and initialize variable to ste random number VB Functions and Operats Page 9 of 11

End Sub Dim randomnumber As Integer 'Randomly generate and ste random number randomnumber = rnd.next() 'Output and fmat the random number lblnumber.text = FmatNumber(randomNumber, 0,,, TriState.True) When you run the program, and click the GENERATE button, a random number is outputted in the label. SPECIFYING A RANGE OF NUMBERS We can specify a range of numbers by passing a single argument to the Next() method. F example, if I wanted to generate a random number between 0 and 5, I would use the Next() method as follows: randomnumber = rnd.next(6) When a single argument is passed to the Next() method, the values returned by Next() will be in the range from 0 to (but not including) the value of that argument. So, in the above example, the program will generate one of six possible numbers in the range 0-5. Let s say I wanted to generate a random number between 1 and 6. In this case, there are two ways we can do this. The first is simply pass a single argument to the Next() method to represent the amount of possible values the program will generate and simply add the minimum value to the equation, as follows: randomnumber = rnd.next(6) + 1 Alternatively, you can produce the same result by passing two arguments to the Next() method: the first representing the minimum value in our range and the second representing the maximum value + 1. randomnumber = rnd.next(1, 7) VB Functions and Operats Page 10 of 11

GENERATING FLOATING-POINT VALUES The Random() class includes a NextDouble() method to generate a random floating-point value greater than equal to 0 and less than 1. randomnumber = rnd.nextdouble() To specify a range of values, such as 1.0 10.0, we will need to multiply the result of NextDouble() by the amount of possible integer values - 1 (i.e. 10 1) and then add the minimum value, as follows: randomnumber = rnd.nextdouble() * 9 + 1 VB Functions and Operats Page 11 of 11