Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

Similar documents
Introduction to. second print. Copyright HKTA Tang Hin Memorial Secondary School 2016

Outline. Data and Operations. Data Types. Integral Types

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2017

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

LOOPS. Repetition using the while statement

Introduction to. second print. Copyright HKTA Tang Hin Memorial Secondary School

Section A Arithmetic ( 5) Exercise A

Learning the Language - V

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

WHOLE NUMBER AND DECIMAL OPERATIONS

Expressions and Casting

Topic 2: Decimals. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

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

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

The Big Python Guide

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Topics. Chapter 5. Equality Operators

Functions, Randomness and Libraries

A Balanced Introduction to Computer Science, 3/E

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

4. Use a loop to print the first 25 Fibonacci numbers. Do you need to store these values in a data structure such as an array or list?

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

Chapter 3 Problem Solving and the Computer

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

C Functions. 5.2 Program Modules in C

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Object Oriented Programming with Visual Basic.Net

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

3 The L oop Control Structure

The Math Class. Using various math class methods. Formatting the values.

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Summer Packet 7 th into 8 th grade. Name. Integer Operations = 2. (-7)(6)(-4) = = = = 6.

Other Loop Options EXAMPLE

Chapter 4: Basic C Operators

Decisions, Decisions. Testing, testing C H A P T E R 7

2009 Fall Startup Event Thursday, September 24th, 2009

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

VB CONSOLE SUMMER WORK. Introduction into A Level Programming

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

The little book of programming challenges

Operators & Expressions

Downloaded from Chapter 2. Functions

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CS110: PROGRAMMING LANGUAGE I

Random Numbers. Chapter 14

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

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

Topic 2: Introduction to Programming

More about Loops and Decisions

4. Java Project Design, Input Methods

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Expressions and Variables

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Topic 3: Fractions. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra

Text Input and Conditionals

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

AP Computer Science A. Return values

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

VBScript: Math Functions

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Introduction to C# Applications

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Lecture Notes on Contracts

(Subroutines in Visual Basic)

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

NUMBERS AND NUMBER RELATIONSHIPS

Unit 3. Operators. School of Science and Technology INTRODUCTION

Building Java Programs

Building Java Programs

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Building Java Programs

Unit 1 Lesson 4. Introduction to Control Statements

FUNctions. Lecture 03 Spring 2018

Building Java Programs

>>> * *(25**0.16) *10*(25**0.16)

Functions and Procedures. Functions. Built In Functions. Built In Functions in VB FIT 100 FIT 100

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Building Java Programs

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

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

UNIT- 3 Introduction to C++

CHAPTER 4: DECIMALS. Image from Microsoft Office Clip Art CHAPTER 4 CONTENTS

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

What did we talk about last time? Examples switch statements

Project 3: RPN Calculator

UNIT 9A Randomness in Computation: Random Number Generators

5. Selection: If and Switch Controls

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Prime Time (Factors and Multiples)

At full speed with Python

Arithmetic and Bitwise Operations on Binary Data

Transcription:

Introduction to 2 VISUAL BASIC 2016 edition Copyright HKTA Tang Hin Memorial Secondary School 2016

Table of Contents. Chapter....... 1.... More..... on.. Operators........................................ 1.1....... Assignment.......... operators....................................................... 1.2....... Exercise.............................................................. Chapter....... 2.... Procedures............................................... 2.1....... Function................................................................. 2.2....... Sub................................................................. 2.3....... More..... about..... parameters....................................................... 2.4....... Exercise.............................................................. Chapter....... 3.... Mathematics........... in.. VB.NET.................................. 3.1....... Exercise.............................................................. Chapter....... 4.... Random....... Numbers........................................ 4.1....... Rnd.... function............................................................. 4.2....... Simulating......... dice........................................................ 4.3....... Random....... integers........ in.. a. range............................................... 4.4....... Exercise.............................................................. Chapter....... 5.... Do Loop......... Statement...................................... 5.1....... Learning........ by.. examples....................................................... 5.2....... Exit.... Do.. and.... Continue......... Do.............................................. 5.3....... Exercise.............................................................. Glossary...................................................... 3 6 7 8 9 14 16 19 20 23 24 25 27 28 30 31 32 36 40 42

More on Operators 3 Chapter 1 More on Operators We have learnt how to do calculation and make decisions in VB.NET. In this chapter, we will learn a few extra operators. Order of operations As listed in the last chapter, the evaluation of expressions in Visual Basic is ordered by its operator precedence below. 11 (Highest) Exponentiation ^ 10 Unary identity and negation (unary)+ (unary) 9 Multiplication and floating-point division * / 8 Integer division \ 7 Modulus arithmetic Mod 6 Addition and subtraction + 5 String concatenation & 4 Relational/comparison operators = <> < <= > >= 3 Negation Not 2 Conjunction And 1 (Lowest) Inclusive disjunction Or Now we continue to the operators that was not introduced before, i.e. \, Mod, &, and the unary operators.

4 Introduction to Visual Basic (Part 2) Division with remainders The operators \ and Mod are used for division with remainders. \ means getting the quotient of the division, and Mod means getting the remainder. Here are a few examples: VB.NET Expression Result VB.NET Expression Result 75 \ 8 9 75 Mod 8 3-75 \ 8-9 -75 Mod 8-3 75 \ -8-9 75 Mod -8 3-75 \ -8 9-75 Mod -8-3 Now we discuss about the signs of the results. In the example above, we find that the signs of both 75 (dividend) and 8 (divisor) are considered in \, but only the sign of 75 is considered in Mod. Now we go to floating point numbers. The results may not be obvious at all. VB.NET Expression Result VB.NET Expression Result 31.25 \ 4.5 7 31.25 Mod 4.5 4.25 31.25 \ 5.5 5 31.25 Mod 5.5 3.75 The \ operator converts numbers into integers before division, while Mod does not. Floating point numbers are converted to integers in a way not obvious to us: 4.5 is rounded off to 4, but 5.5 is rounded off to 6. Do not use \ and Mod with floating-point numbers unless you know what are you doing. Unary operators There are two unary operators in VB.NET, namely identity ( + ) and negation( - ). They correspond to the positive and the negative signs of Mathematics respectively. In fact, only the unary - is useful.

String concatenation More on Operators 5 To join strings together, i.e. concatenate the strings, we use the & operator or the + operator. & is preferred over + because & is defined for strings only. In contrast, + is used mainly for addition. Here are a few examples: "note" & "pad" VB.NET Expression Result "notepad" 5 & 4 * 6 "524" As shown in the example, & converts it s operands into strings implicitly. Note that the conversion is not done in +, so unintended results and even errors may happen. Class work No space is added to the strings during a concatenation. Evaluate the following VB.NET expressions: VB.NET Expression Result "con" & "cent" & "rated" 4 * 3 & 5 * 2 9-25 / 2 * 3 9-25 \ 2 * 3-35 Mod 3 ^ 3 a a a a ( 1 2 ) 123

6 Introduction to Visual Basic (Part 2) 1.1 Assignment operators One of the most common operations in a program is to increase and decrease the value of a variable. See the following example for an idea. ' Assigns the value 10 to the variable. applessold = 10 ' The following statement increases "applessold" by one. applessold = applessold + 1 ' The variable now holds the value 11. In the example, the statement applessold = applessold + 1 increases the value of the variable applessold by 1. You may also write applessold += 1 instead, i.e. ' Assigns the value 10 to the variable. applessold = 10 ' The following statement increases "applessold" by one. applessold += 1 ' The variable now holds the value 11. In the second example, += is an assignment operator, which adds a certain value to a variable. -=, *=, /=, \=, ^= and &= are also assignment operators, which have similar meanings. Class Work Express the following actions into VB.NET code: Action Increase x by 100 Decrease y by 5 Multiple product by -3 VB.NET statement Add sugar to the end of the str1

1.2 Exercise Exercise 7 1. Write a program that accepts the hour of a day (from 0 to 23). Then calculate the hour three hours later. The output of the program should match the sample below: Enter the hour (0-23): 22 Three hours later, the time is 1:00 2. Write a program that accepts the hours (from 0 to 23) of the start time and the end time. Find the difference of the time, provided that the difference is between 1 and 24 hours (inclusive). The output of the program should match the sample below: Enter the start hour (0-23): 22 Enter the end hour (0-23): 12 The time elapsed is 14 hours.

8 Introduction to Visual Basic (Part 2) Chapter 2 Procedures When we perform some operations repeatedly, we group the operations together into procedures. This avoids the problem of copying the same, or similar code, everywhere in your source. In Visual Basic.NET, a procedure that returns a value is called a Function, and a procedure without a return value is called a Sub. You have already encountered a few procedures before. Sub Main(), Console.WriteLine, Console.Write and Console.ReadLine are all procedures.

2.1 Function Function 9 A Function is a procedure that returns a value. Here is the syntax of a function: Function NameOfFunction(parameterList) As ReturnType... Return returnvalue... End Function The following are some components of a function: Component Name of the function Parameter list Return statement Return type Details You should give the function a name (with a few words in CamelCase, e.g. AreaOfTriangle) that describes what the function do. If the name is valid for a variable, then it is valid also for a function. Usually the inputs of the function. The list is written in a comma separated list of parameters (okay to be empty). Details will be discussed later in this chapter. Ends the function immediately, and outputs a return value to the caller. Multiple Return statements can be present in a single function, and this is useful with If Then Else statements. The data type ( Integer, Double or others) of the return value.

10 Introduction to Visual Basic (Part 2) Example: area of a triangle Here is a function that calculates the area of a triangle: Module Module1 Function AreaOfTriangle(base As Double, height As Double) As Double Return base * height / 2 End Function Sub Main() Dim base1 As Double = 3 Dim height1 As Double = 4 Console.WriteLine("The area of triangle one is {0}.", AreaOfTriangle(base1, height1)) Dim base2 As Double = 5 Dim height2 As Double = 6 Console.WriteLine("The area of triangle two is {0}.", AreaOfTriangle(base2, height2)) Console.ReadLine() End Sub End Module The area of triangle one is 6. The area of triangle two is 15. In VB.NET, no procedures can be put inside other procedures. They are supposed to be inside a Module only. As the first example, the function above is very simple. It is still a good idea to write a function because we do not want to enter the formula twice. Writing the same code multiple times makes it more probable to introduce bugs.

Example: inputting values Function 11 Here is a function that allow the user to enter numbers: Module Module1 Function ReadDoubleWithPrompt(prompt As String) As Double Console.Write(prompt) Return Console.ReadLine() End Function Sub Main() Dim base As Double = ReadDoubleWithPrompt("Enter the base: ") Dim height As Double = ReadDoubleWithPrompt("Enter the height: ") Console.WriteLine("The area of the triangle is {0}.", base * height / 2) Console.ReadLine() End Sub End Module Enter the base: 4 Enter the height: 8 The area of the triangle is 16. You may have already noticed that AreaOfTriangle in the last example can also be used in this example.

12 Introduction to Visual Basic (Part 2) Example: converting marks into grades Here is an example using If Then statements. Module Module1 Function GetGradeByMark(mark As Double) As String If mark >= 80 Then Return "A" End If If mark >= 70 Then Return "B" End If If mark >= 50 Then Return "C" End If Return "F" End Function Sub Main() Console.Write("Enter the mark: ") Dim mark As Double = Console.ReadLine() Console.WriteLine("The grade is {0}.", GetGradeByMark(mark)) Console.ReadLine() End Sub End Module Enter the mark: 50 The grade is C. Remember to return a value in all cases. Avoid Else or ElseIf keyword after a Return statement if possible.

Parameters, parameter list and arguments Function 13 As shown in the examples, the parameter list is having a syntax similar to Dim statement, which is: name1 As datatype1, name2 As datatype2,... Each part of the parameter list is a parameter. A parameter is a special variable that receives data from callers. You can have any number of parameters in a function. Some functions have no parameter (e.g. Console.ReadLine ), and some have a lot of parameters. When you use the function, you are going to call it. The place you call the function is called the caller or the call site. Each time you call the function, you can supply different arguments to the same function. For example: Dim area1 As Double = AreaOfTriangle(base1, height1) Dim area2 As Double = AreaOfTriangle(base2, height2) The arguments of your function call should match the definitions of the function. Class Work Write down a Function statement for the following. Remember to name the function and parameters properly. 1. A function that finds the perimeter of a rectangle, where the width and the height of the rectangle are given. 2. A function that finds the percentage change, where the original value and the new value are given. 3. A function that check if the student gets a pass in all subjects: Chinese, English and Mathematics. 4. A function that checks if the content of a string is a number, e.g. "12345".

14 Introduction to Visual Basic (Part 2) 2.2 Sub A Sub is a procedure that does not return a value. Here is the syntax: Sub NameOfSub(parameterList)... Return ' Use only if you need to return early... End Sub Like a function, Return statements can be used in a Sub. Since no value is being returned, the Return statement is just the single word Return. You can use Return statements in Sub Main(). By exiting Sub Main(), these Return statements end the program immediately.

Example Sub 15 Module Module1 Sub ProcessMark(mark As Double) If mark < 0 Or mark > 100 Then Console.WriteLine("Invalid mark: {0}", mark) Return End If If mark >= 50 Then Console.WriteLine("Pass") Else Console.WriteLine("Fail") End If End Sub Sub Main() Console.Write("Enter the mark of subject 1: ") Dim mark1 As Double = Console.ReadLine() ProcessMark(mark1) Console.Write("Enter the mark of subject 2: ") Dim mark2 As Double = Console.ReadLine() ProcessMark(mark2) Console.ReadLine() End Sub End Module Enter the mark of subject 1: 45 Fail Enter the mark of subject 2: 50 Pass

16 Introduction to Visual Basic (Part 2) 2.3 More about parameters What happens when I change the value of a parameter inside a Function or Sub? Unless you specify otherwise (see the section below), the arguments are passed by value. It means copies of the variables are passed into the procedure. If any parameters is changed in the procedure, only the copy is changed. The original value is not changed with the copy. Changing the value of an argument passed by value inside a procedure is bad for readability. Do this with care. Appendix: Passing arguments by reference To allow procedures to change the value of the original argument, you can set the parameter to pass by reference. In VB.NET, this is done by adding the ByRef keyword before the parameter. Passing parameters by reference is used mainly to allow the use of more than one output value in a function. to avoid the performance penalty of copying a large data structure. However, with the internal use of reference types in VB.NET, we usually do not incur the performance penalty by passing by value.

Example: ByRef keyword More about parameters 17 Module Module1 ' x is passed to PassByVal by value. Sub PassByVal(x As Integer) x = 10 End Sub ' x is passed to PassByVal by reference. Sub PassByRef(ByRef x As Integer) x = 10 End Sub Sub Main() Dim value As Integer = 1 ' The value doesn't change here when passed by value. PassByVal(value) Console.WriteLine("After PassByVal: {0}", value) ' The value DOES change when passed ByRef. PassByRef(value) Console.WriteLine("After PassByRef: {0}", value) Console.ReadLine() End Sub End Module After PassByVal: 1 After PassByRef: 10

18 Introduction to Visual Basic (Part 2) Example: using a sub to swap numbers Module Module1 Sub SwapIntegers(ByRef first As Integer, ByRef second As Integer) Dim tempvalue As Integer = first first = second second = tempvalue End Sub Sub Main() Dim x As Integer = 3 Dim y As Integer = 4 Console.WriteLine("Before swap: x = {0}, y = {1}", x, y) SwapIntegers(x, y) Console.WriteLine("After swap: x = {0}, y = {1}", x, y) Console.ReadLine() End Sub End Module Before swap: x = 3, y = 4 After swap: x = 4, y = 3 Appendix: Value type and reference type in.net Some data types are stored internally as a reference to some underlying data, e.g. String. These are known as reference types in.net platform. In contrast, Integer, Single, Double and Boolean are value types. This has some implications on passing arguments in procedures, which are discussed in https://msdn.microsoft.com/en-us/library/eek064h4.aspx and http://netinformations.com/faq/general/valuetype-referencetype.htm.

2.4 Exercise Exercise 19 1. Write two functions to calculate the area and the perimeter of a rectangle from its length and width. Use these functions to create a program that produce output that matches the following sample: Enter the length of the rectangle: 10 Enter the width of the rectangle: 8 The area of the rectangle is 80, and the perimeter is 36. 2. Write a function that checks if a child is eligible for free entry. The child is eligible for free entry if he or she is aged under 3 and is shorter than 90 cm. Use the function to create a program that produce output that matches the following sample: Enter the age: 2 Enter the height (in cm): 90 The child is NOT eligible for free entry. Enter the age: 1 Enter the height (in cm): 89.5 The child is eligible for free entry.

20 Introduction to Visual Basic (Part 2) Chapter 3 Mathematics in VB.NET This chapter introduces some mathematical functions and constants used in VB.NET. Mathematical functions Function Description Example Result Math.Sqrt Finds the square root. Math.Sqrt(4) 2 Math.Max Math.Min Math.Round Math.Floor (or Int) Math.Ceiling Math.Truncate (or Fix) Math.Abs Math.Sign Returns the larger of two numbers. Returns the smaller of two numbers. Rounds off to the nearest integer, or to a specified number of decimal places. Rounds down to the nearest integer. Rounds up to the nearest integer. Finds the integral part. Finds the absolute value (remove negative sign). The sign of the number (positive: 1, zero: 0, negative: -1). Math.Max(2, 5) 5 Math.Max(2, 5) 2 Math.Round(11.56) Math.Round(11.56, 1) Math.Floor(2.3) Math.Floor(-2.3) Math.Ceiling(2.3) Math.Ceiling(-2.3) Math.Floor(2.3) Math.Floor(-2.3) Math.Abs(-4) Math.Abs(3) 12 11.5 2-3 3-2 2-2 4 3 Math.Sign(-5) -1

Mathematical constants Mathematics in VB.NET 21 Constant Description Data type Value Math.PI The value of π. Double 3.141592653589793 Data types used in mathematics functions Here are the data types of the inputs and outputs of the mathematical functions. Function Input data type Output data type Math.Sqrt, Math.Round, Math.Floor, Math.Ceiling Double Same as the input Math.Max, Math.Min Double, Single, Integer Note: both inputs must have the same data type. Same as the input Math.Abs, Int, Fix Double, Single, Integer Same as the input Math.Sign Double, Single, Integer Integer

22 Introduction to Visual Basic (Part 2) Class Work Convert the following expressions into VB.NET statement Mathematical expression VB.NET statement a = x + 1 a = Math.Sqrt(x + 1) r = 4 V = 3 3 πr [Take π = Math.PI ] a = max(x, y 1) p = min(0.5, 1 x 2 ) x = 2 x + x 3 2 1 + 1 + a

3.1 Exercise Exercise 23 1. Write a program that calculates the total surface area of a circular cone. The 2 2 formula of the total surface area is πr ( r + h + r ), where r is the base radius, and h is the height. Round off the answer to four decimal places. The output of the program should match the sample below: Enter the base radius: 1.2 Enter the height: 3.4 The total surface area is 18.1165 square units. 2. Write a program to check if a non-negative integer is a square number. The program should not accept decimals or negative numbers. The output of the program should match the sample below: Enter a number: 2 2 is NOT a square number. Enter a number: 25 25 is a square number. Enter a number: -3 You should enter a non-negative integer. Enter a number: 6.25 You should enter a non-negative integer.

24 Introduction to Visual Basic (Part 2) Chapter 4 Random Numbers Random numbers are an important aspect of programs. In computer games, random numbers are used to simulate dice. Some algorithms requires the use of random numbers to do calculations. Random numbers are also used to generate the secret keys, which is needed for encryption to work. How do computer generate random numbers There are two kinds of random number generators. The first kind is called pseudorandom number generators (PRNGs), which does not use a real random source. Randomness is simulated using an algorithm. The second kind of random number generator gather randomness (or entropy) from some physical phenomenon, such as radioactive source or atmospheric noise. This kind of generators provides true randomness comparable to dice. However, the speed of generation of randomness is slow. In VB.NET, two PRNGs are provided in the language. We will study one of them: Rnd() and Randomize(), to learn how to use random numbers in programs.

4.1 Rnd function Rnd function 25 The Rnd function returns a number less than one, but greater than or equal to zero, i.e. 0 x < 1 The syntax is of Rnd function is simply Rnd(), and it returns a random number in the Single data type. The following program outputs a result of Rnd ten times. Repeat running the program to see what is wrong. Sub Main() Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.WriteLine(Rnd()) Console.ReadLine() End Sub 0.7055475 0.533424 0.5795186 0.2895625 0.301948 0.7747401 0.01401764 0.7607236 0.81449 0.7090379

26 Introduction to Visual Basic (Part 2) Seeding the Rnd function with Randomize() To make the Rnd function generate different sequence of numbers, we call the Randomize function before using the Rnd function. Randomize gives a seed to the random number generator used by Rnd. Randomize should be called only once in the whole program. After the corrections, the program looks like: Sub Main() Randomize() Console.WriteLine(Rnd()) Console.WriteLine(Rnd())... End Sub This time the outputs are different every time the program is run: 0.8079645 0.101173 0.2512715 0.1493037 0.09772438 0.262411 0.9260049 0.8997617 0.7723758 0.7103807

5 1 4.2 Simulating dice Simulating dice 27 In this section, we use Rnd function to simulate a die (singular of dice). What we need to do is the following: Dim value As Integer = Int(Rnd() * 6) + 1 It is okay to put + 1 either inside or outside the brackets. If we are doing this in strict mode, then we do the following: Dim value As Integer = CInt(Int(Rnd() * 6)) + 1 The function CInt converts a number into Integer data type. In strict mode, the conversion from Single to Integer must be done manually. To illustrate this statement, we list all possible values of Rnd() in the table below: Rnd() Rnd() * 6 Int(Rnd() * 6) Int(Rnd() * 6) + 1 0 and < 6 0 and < 1 0 1 6 1 and < 6 2 1 and < 2 6 2 and < 6 3 6 3 and < 6 4 6 4 and < 6 5 6 and < 1

3 1 28 Introduction to Visual Basic (Part 2) 4.3 Random integers in a range We can modify the statement Int(Rnd() * 6) + 1 to generate random integers that fall with in a certain range. Take Int(Rnd() * 4) + 8 as an example: Rnd() Rnd() * 4 Int(Rnd() * 4) Int(Rnd() * 4) + 8 0 and < 4 0 and < 1 4 1 and < 4 2 4 2 and < 4 3 4 and < 1 From the table, we know that the statement generates random integers from 8 to 11 inclusive. Also, 4 is the number of possible outcomes, and 8 is the minimum outcome. The total number of possible outcomes can be calculated by max min + 1, where max and min are the maximum and minimum outcome respectively. Therefore, we can generate integers inside a range using the formula below: Or in strict mode: [variable] = Int(Rnd() * (max min + 1)) + min [variable] = CInt(Int(Rnd() * (max min + 1))) + min You can create a function with the code above, to avoid repeating the formula every time you use it.

Class work Random integers in a range 29 Write a Visual Basic statement to generate the random numbers below: Random number VB code An integer from 1 to 6 inclusive Int(Rnd() * 6) + 1 An integer from 1 to 5 inclusive An integer from 10 to 20 inclusive An integer from 25 to 30 inclusive An integer from 50 to 100 inclusive An integer from 0 to 2 inclusive An integer from 5 to 5 inclusive The sum of the values of 2 dice (the possible values of each die are 1 to 6)

30 Introduction to Visual Basic (Part 2) 4.4 Exercise 1. Write a program that throws two dice, one for the player and the other for the computer. Display the values of both dice. Also, compare the values of the dice, and the one with the larger value wins. Output You win!, You lose! or Draw! depending on the value of the dice. The output of the program should match the sample below: Player: 4 Computer: 2 You win! 2. Write a program that asks the player to do additions. The computer generates two random numbers from 11 to 99, and ask the user to enter the sum. The output of the program should match the sample below: What is the result of 34 + 56? 90 You are correct! What is the result of 26 + 47? 63 You are wrong! 3. Modify the program in the previous question, that the program generates a random sign in addition to two random numbers. You may start working with only + and sign, and continue with and later. You can also change the limits of the numbers, and even let the user decides them. Some special considerations should be made for subtraction and division.

Chapter 5 Do Loop Statement Do Loop Statement 31 To make a program to feel like a real program you need some looping, i.e. repeating the execution of some instructions. Now we learn the Do Loop statement, which is the most versatile of all loop structures. The syntax of a Do Loop statement is listed below: Do { While Until } condition [ statements ] Loop -or- Do [ statements ] Loop { While Until } condition -or- Do [ statements ] Loop The Do Loop statement repeats the execution of the statements inside indefinitely, While or Until some condition is true. Each time the statements inside are executed is called an iteration. The condition can be put either after Do or after Loop. If the condition is put after Do, then the condition is tested in the first iteration. And the condition is not satisfied, the loop will not be run even once. In the other way, if the condition is put after Loop, then the condition is not tested in the first iteration. In this case, the loop is guaranteed to run at least once. Of course, you can also choose not to include a condition at all. In this case the Do Loop statement ends only with some other means (e.g. by a Exit Do statement, which is introduced later).

32 Introduction to Visual Basic (Part 2) 5.1 Learning by examples To learn looping it is easiest to learn by examples. Example: playing a game again In this example, the computer ask whether a user should play a game again or not. If the user presses Y, then the game is played again. Otherwise, the game quits. Sub Main() Randomize() Console.WriteLine("Lucky dice - you win if you roll a 6.") Dim playagain As String Do Dim die As Integer = CInt(Int(Rnd() * 6)) + 1 If die = 6 Then Console.WriteLine("You have rolled 6! You win!") Else Console.WriteLine("You have rolled {0}. You lose!", die) End If Console.Write("Do you want to play again? (Y/N) ") playagain = Console.ReadLine() Loop While playagain = "Y" Or playagain = "y" End Sub Lucky dice - you win if you roll a 6. You have rolled 4. You lose! Do you want to play again? (Y/N) Y You have rolled 5. You lose! Do you want to play again? (Y/N) y You have rolled 6! You win! Do you want to play again? (Y/N) n

Learning by examples 33 Some of you might have asked: what will happen if I enter something other than Y or N? In the program above, it simply treats the answer as an N. Of course, you may like to repeat the question in this case. This can be done with nested loops. For example: Sub Main() Randomize() Console.WriteLine("Lucky dice - you win if you roll a 6.") Dim playagain As String Do Dim die As Integer = CInt(Int(Rnd() * 6)) + 1 If die = 6 Then Console.WriteLine("You have rolled 6! You win!") Else Console.WriteLine("You have rolled {0}. You lose!", die) End If Do Console.Write("Do you want to play again? (Y/N) ") playagain = Console.ReadLine() Loop Until playagain = "Y" Or playagain = "y" Or playagain = "N" Or playagain = "n" Loop While playagain = "Y" Or playagain = "y" End Sub Lucky dice - you win if you roll a 6. You have rolled 3. You lose! Do you want to play again? (Y/N) ab Do you want to play again? (Y/N) yes Do you want to play again? (Y/N) y You have rolled 2. You lose! Do you want to play again? (Y/N) no Do you want to play again? (Y/N) n

34 Introduction to Visual Basic (Part 2) To make the program more maintainable, we can break down the program into procedures. Besides being easier to read, individual procedure can also be copied into different programs, saving time for development. For example, the previous program can be rewritten in the following way: Sub DoLuckyDraw() Dim die As Integer = CInt(Int(Rnd() * 6)) + 1 If die = 6 Then Console.WriteLine("You have rolled 6! You win!") Else Console.WriteLine("You have rolled {0}. You lose!", die) End If End Sub Function ShouldPlayAgain() As Boolean Dim playagain As String Do Console.Write("Do you want to play again? (Y/N) ") playagain = Console.ReadLine() Loop Until playagain = "Y" Or playagain = "y" Or playagain = "N" Or playagain = "n" Return playagain = "Y" Or playagain = "y" End Function Sub Main() Randomize() Console.WriteLine("Lucky dice - you win if you roll a 6.") Do DoLuckyDraw() Loop While ShouldPlayAgain() End Sub

Example: reversing the digits of an integer Learning by examples 35 The following example shows how a Do Loop statement is used to do calculations. Note: arguments are passed to reversedigits by value. Function reversedigits(n As Integer) As Integer Dim reversed As Integer = 0 Do While n > 0 Dim digit = n Mod 10 n \= 10 reversed = reversed * 10 + digit Loop Return reversed End Function Sub Main() Console.Write("Enter an integer: ") Dim n As Integer = Console.ReadLine() Console.WriteLine( "After reversing the digits, the result is {0}.", reversedigits(n)) Console.ReadLine() End Sub Enter an integer: 13579 After reversing the digits, the result is 97531. It is easier to get the last digit of an integer than the first digit.

36 Introduction to Visual Basic (Part 2) 5.2 Exit Do and Continue Do Exit Do means to exit the Do Loop statement immediately. Control is transferred to the statement after the loop. Continue Do means to bypass everything in the current iteration. Control goes to the next iteration if the loop condition is satisfied. Example: total and average marks Dim totalmarks As Double = 0 Dim numsubjects As Integer = 0 Do Console.Write( "Enter the mark of the next subject (-1 to quit): ") Dim mark As Double = Console.ReadLine() If mark = -1 Then Exit Do End If If mark < 0 Or mark > 100 Then Console.WriteLine("Invalid mark ignored.") Continue Do End If totalmarks += mark numsubjects += 1 Loop Console.WriteLine() Console.WriteLine("Number of subjects: {0}", numsubjects) Console.WriteLine("Total marks: {0}", totalmarks) Console.WriteLine("Average mark: {0}", totalmarks / numsubjects) Console.ReadLine()

Exit Do and Continue Do 37 Enter the mark of the next subject (-1 to quit): 23 Enter the mark of the next subject (-1 to quit): 80 Enter the mark of the next subject (-1 to quit): 106 Invalid mark ignored. Enter the mark of the next subject (-1 to quit): 66.5 Enter the mark of the next subject (-1 to quit): -1 Number of subjects: 3 Total marks: 169.5 Average mark: 56.5 Exit Do and Continue Do are usually used with If Then statements. Use Exit Do if you want to quit a loop in the middle of an iteration. Use Continue Do to skip data that you do not want to process.

38 Introduction to Visual Basic (Part 2) Example: high-low guessing game Finally we have a more advanced example: a game utilizing everything we have learnt. Try to figure out the logic behind the game! Function GetRandomInteger() As Integer Return CInt(Int(Rnd() * 100)) + 1 End Function Sub Main() Randomize() Console.WriteLine("Number guessing game") Console.WriteLine("====================") Console.WriteLine("The computer will pick and show a random number from 1 to 100.") Console.WriteLine("You need to guess whether the next number is higher or lower.") Console.WriteLine("Try to guess correctly as long as you can.") Console.WriteLine() Dim score As Integer = 0 Dim num As Integer = GetRandomInteger() Do Console.Write("The number is {0}. Higher / lower (H/L)? ", num) Dim choice As String = Console.ReadLine() Do While choice <> "H" And choice <> "h" And choice <> "L" And choice <> "l" Console.Write("Please enter ""H"" or ""L"". Higher / lower (H/L)? ") choice = Console.ReadLine() Loop Dim nextnum As Integer = GetRandomInteger() If nextnum = num Then Console.WriteLine("The number is {0}. You lose no matter what you guess!", nextnum) Exit Do End If If nextnum > num And (choice <> "H" And choice <> "h") Or nextnum < num And (choice <> "L" And choice <> "l") Then Console.WriteLine("The number is {0}. You have lost!", nextnum) Exit Do End If Loop num = nextnum score += 1 Console.WriteLine() Console.WriteLine("Your score: {0}", score) Console.ReadLine() End Sub

Exit Do and Continue Do 39 Number guessing game ==================== The computer will pick and show a random number from 1 to 100. You need to guess whether the next number is higher or lower. Try to guess correctly as long as you can. The number is 23. Higher / lower (H/L)? H The number is 37. Higher / lower (H/L)? S Please enter "H" or "L". Higher / lower (H/L)? H The number is 93. Higher / lower (H/L)? L The number is 78. Higher / lower (H/L)? L The number is 29. Higher / lower (H/L)? H The number is 47. Higher / lower (H/L)? L The number is 4. Higher / lower (H/L)? H The number is 47. Higher / lower (H/L)? H The number is 40. You have lost! Your score: 7 Feel free to use Exit Do and Continue Do to express your intent in the code. You should write the exact logic you are thinking of.

40 Introduction to Visual Basic (Part 2) 5.3 Exercise 1. Write a program that draws random prizes. There should be a 70% chance to win a small prize, a 25% chance to win a big prize, and a 5% chance to win a JUMBO prize. After the lucky draw you should ask the user whether to draw again. The output of the program should match the following sample: Lucky Draw ========== You have won a JUMBO prize! Draw again? (Y/N) Y You have won a small prize! Draw again? (Y/N) n 2. Write a program that play the number guessing game. The program should generate a random secret number from 1 to 100, and let the user guess it. It is okay for skip the number of guesses in your first version, and add it back later. Number Guessing Game ==================== The computer has a secret number between 1 and 100. Guess the number in as few tries as possible. Enter your guess: 50 Too large! Enter your guess: 25 Too small! Enter your guess: 37 Too small! Enter your guess: 44 Correct! You have guessed 4 times.

Exercise 41 3. Write a program that plays rock-paper-scissors. The program should continue to play until the player ends the program. You can follow the sample output below: ROCK, PAPER and SCISSORS Type END to end the game. Rock, paper or scissors? (R/P/S/END) R The computer played SCISSORS. You have won! The score is now 1:0 Rock, paper or scissors? (R/P/S/END) C Please enter "R", "P" or "S". Rock, paper or scissors? (R/P/S/END) S The computer played ROCK. You have lost! The score is now 1:1 Rock, paper or scissors? (R/P/S/END) P The computer played PAPER. Draw! The score is now 1:1 Rock, paper or scissors? (R/P/S/END) END 4. Write a program that finds the greatest common divisor (GCD) of two integers using Euclidean algorithm.

42 Introduction to Visual Basic (Part 2) Glossary argument A piece of data that is passed into a procedure. assignment operator An operator that assigns a value to a variable. call The action of using a procedure. call site The position of the code that calls a procedure. Also known as caller. concatenate The operation to join two strings together. control The position where the next computer instruction is executed. iteration When a block of statements is executed multiple times, each repetition of these statements is called an iteration. looping Executing a block of statements multiple times. nested loop Putting a loop within another loop. parameter A special variable defined in a procedure, that can receive data from call sites. PRNG Pseudo-random number generator, that does not use a random source. It simulate randomness using an algorithm. procedure A part of a program, that is packaged as a single unit. Also known as subroutine, function or subprogram.

Glossary 43 seed A number used to initialize a random number generator. In VB.NET the current time is used for seeding.