Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

Size: px
Start display at page:

Download "Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016"

Transcription

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

2 Table of Contents. Chapter More..... on.. Operators Assignment operators Exercise Chapter Procedures Function Sub More..... about..... parameters Exercise Chapter Mathematics in.. VB.NET Exercise Chapter Random Numbers Rnd.... function Simulating dice Random integers in.. a. range Exercise Chapter Do Loop Statement Learning by.. examples Exit.... Do.. and.... Continue Do Exercise Glossary

3 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 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 \ Mod \ Mod \ Mod \ 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 \ Mod \ Mod 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.

5 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 * \ 2 * 3-35 Mod 3 ^ 3 a a a a ( 1 2 ) 123

6 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

7 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 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.

9 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 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.

11 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 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.

13 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 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.

15 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 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.

17 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 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 and

19 2.4 Exercise Exercise 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 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 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) Math.Sign(-5) -1

21 Mathematical constants Mathematics in VB.NET 21 Constant Description Data type Value Math.PI The value of π. Double 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 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 a

23 3.1 Exercise Exercise 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 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: 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 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.

25 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

26 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:

27 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) and < 6 0 and < and < and < and < and < and < and < 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) and < 4 0 and < and < and < 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.

29 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 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 ? 90 You are correct! What is the result of ? 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.

31 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 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

33 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 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

35 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: After reversing the digits, the result is It is easier to get the last digit of an integer than the first digit.

36 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()

37 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: 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 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

39 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 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.

41 Exercise 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 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.

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

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

Introduction to. second print. Copyright HKTA Tang Hin Memorial Secondary School 2016 Introduction to 2 VISUAL BASIC 2016 edition second print Copyright HKTA Tang Hin Memorial Secondary School 2016 Table of Contents. Chapter....... 1.... More..... on.. Operators........................................

More information

Outline. Data and Operations. Data Types. Integral Types

Outline. Data and Operations. Data Types. Integral Types Outline Data and Operations Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations Data and Operations

More information

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2017

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2017 Introduction to 3 VISUAL BASIC 2016 edition Copyright HKTA Tang Hin Memorial Secondary School 2017 Table of Contents. Chapter....... 1.... Select Case........... Statement....................................

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

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

Introduction to. second print. Copyright HKTA Tang Hin Memorial Secondary School Introduction to 1 VISUAL BASIC 2016 edition second print Copyright HKTA Tang Hin Memorial Secondary School 2016-17 Table of Contents. Preface....................................................... Chapter.......

More information

Section A Arithmetic ( 5) Exercise A

Section A Arithmetic ( 5) Exercise A Section A Arithmetic In the non-calculator section of the examination there might be times when you need to work with quite awkward numbers quickly and accurately. In particular you must be very familiar

More information

Learning the Language - V

Learning the Language - V Learning the Language - V Fundamentals We now have locations to store things so we need a way to get things into those storage locations To do that, we use assignment statements Deja Moo: The feeling that

More information

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

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013 Expressions and Casting C# Programming Rob Miles Data Manipulation We know that programs use data storage (variables) to hold values and statements to process the data The statements are obeyed in sequence

More information

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

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

WHOLE NUMBER AND DECIMAL OPERATIONS

WHOLE NUMBER AND DECIMAL OPERATIONS WHOLE NUMBER AND DECIMAL OPERATIONS Whole Number Place Value : 5,854,902 = Ten thousands thousands millions Hundred thousands Ten thousands Adding & Subtracting Decimals : Line up the decimals vertically.

More information

Expressions and Casting

Expressions and Casting Expressions and Casting C# Programming Rob Miles Data Manipulation We know that programs use data storage (variables) to hold values and statements to process the data The statements are obeyed in sequence

More information

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

Topic 2: Decimals. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra 41 Topic 2: Decimals Topic 1 Integers Topic 2 Decimals Topic 3 Fractions Topic 4 Ratios Duration 1/2 week Content Outline Introduction Addition and Subtraction Multiplying and Dividing by Multiples of

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

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

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Topics 1. Expressions 2. Operator precedence 3. Shorthand operators 4. Data/Type Conversion 1/15/19 CSE 1321 MODULE 2 2 Expressions

More information

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

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions Grace Murray Hopper Expressions Eric Roberts CSCI 121 January 30, 2018 Grace Hopper was one of the pioneers of modern computing, working with

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

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

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Topics. Chapter 5. Equality Operators

Topics. Chapter 5. Equality Operators Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

More information

Functions, Randomness and Libraries

Functions, Randomness and Libraries Functions, Randomness and Libraries 1 Predefined Functions recall: in mathematics, a function is a mapping from inputs to a single output e.g., the absolute value function: -5 5, 17.3 17.3 in JavaScript,

More information

A Balanced Introduction to Computer Science, 3/E

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 978-0-13-216675-1 Chapter 7 Functions and Randomness 1 Predefined Functions recall: in

More information

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

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN 978-0-13-216675-1 Chapter 7 Functions and Randomness 1 Predefined Functions recall: in

More information

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

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?

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? 1 Practice problems Here is a collection of some relatively straightforward problems that let you practice simple nuts and bolts of programming. Each problem is intended to be a separate program. 1. Write

More information

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

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4. Introduction to Visual Basic and Visual C++ Arithmetic Expression Lesson 4 Calculation I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Arithmetic Expression Using Arithmetic Expression Calculations

More information

Chapter 3 Problem Solving and the Computer

Chapter 3 Problem Solving and the Computer Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an

More information

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

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation Program Development Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr The creation of software involves four basic activities: establishing

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

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

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

More information

Object Oriented Programming with Visual Basic.Net

Object Oriented Programming with Visual Basic.Net Object Oriented Programming with Visual Basic.Net By: Dr. Hossein Hakimzadeh Computer Science and Informatics IU South Bend (c) Copyright 2007 to 2015 H. Hakimzadeh 1 What do we need to learn in order

More information

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

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 Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:

More information

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

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132) BoredGames Language Reference Manual A Language for Board Games Brandon Kessler (bpk2107) and Kristen Wise (kew2132) 1 Table of Contents 1. Introduction... 4 2. Lexical Conventions... 4 2.A Comments...

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

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

The Math Class. Using various math class methods. Formatting the values. The Math Class Using various math class methods. Formatting the values. The Math class is used for mathematical operations; in our case some of its functions will be used. In order to use the Math class,

More information

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

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

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

Summer Packet 7 th into 8 th grade. Name. Integer Operations = 2. (-7)(6)(-4) = = = = 6. Integer Operations Name Adding Integers If the signs are the same, add the numbers and keep the sign. 7 + 9 = 16 - + -6 = -8 If the signs are different, find the difference between the numbers and keep

More information

Other Loop Options EXAMPLE

Other Loop Options EXAMPLE C++ 14 By EXAMPLE Other Loop Options Now that you have mastered the looping constructs, you should learn some loop-related statements. This chapter teaches the concepts of timing loops, which enable you

More information

Chapter 4: Basic C Operators

Chapter 4: Basic C Operators Chapter 4: Basic C Operators In this chapter, you will learn about: Arithmetic operators Unary operators Binary operators Assignment operators Equalities and relational operators Logical operators Conditional

More information

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

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

2009 Fall Startup Event Thursday, September 24th, 2009

2009 Fall Startup Event Thursday, September 24th, 2009 009 Fall Startup Event This test consists of 00 problems to be solved in 0 minutes. All answers must be exact, complete, and in simplest form. To ensure consistent grading, if you get a decimal, mixed

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

VB CONSOLE SUMMER WORK. Introduction into A Level Programming

VB CONSOLE SUMMER WORK. Introduction into A Level Programming VB CONSOLE SUMMER WORK Introduction into A Level Programming DOWNLOAD VISUAL STUDIO You will need to Download Visual Studio Community 2013 to create these programs https://www.visualstudio.com/ en-us/products/visual-studiocommunity-vs.aspx

More information

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

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Contents 1 Introduction...2 2 Lexical Conventions...2 3 Types...3 4 Syntax...3 5 Expressions...4 6 Declarations...8 7 Statements...9

More information

The little book of programming challenges

The little book of programming challenges 24 The little book of programming challenges The following challenges are here to challenge and inspire you as well as help you on your journey to becoming a computational thinker. You may be set these

More information

Operators & Expressions

Operators & Expressions Operators & Expressions Operator An operator is a symbol used to indicate a specific operation on variables in a program. Example : symbol + is an add operator that adds two data items called operands.

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

CS110: PROGRAMMING LANGUAGE I

CS110: PROGRAMMING LANGUAGE I CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters

More information

Random Numbers. Chapter 14

Random Numbers. Chapter 14 B B Chapter 14 Random Numbers Many events in our lives are random. When you enter a full parking lot, for example, you drive around until someone pulls out of a parking space that you can claim. The event

More information

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

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

More information

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

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1 Chapter 2 Input, Processing, and Output Fall 2016, CSUS Designing a Program Chapter 2.1 1 Algorithms They are the logic on how to do something how to compute the value of Pi how to delete a file how to

More information

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

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary Topic 2 1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary Arithmetic Operators C++ has the same arithmetic operators as a calculator:

More information

Topic 2: Introduction to Programming

Topic 2: Introduction to Programming Topic 2: Introduction to Programming 1 Textbook Strongly Recommended Exercises The Python Workbook: 12, 13, 23, and 28 Recommended Exercises The Python Workbook: 5, 7, 15, 21, 22 and 31 Recommended Reading

More information

More about Loops and Decisions

More about Loops and Decisions More about Loops and Decisions 5 In this chapter, we continue to explore the topic of repetition structures. We will discuss how loops are used in conjunction with the other control structures sequence

More information

4. Java Project Design, Input Methods

4. Java Project Design, Input Methods 4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

More information

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

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

More information

Expressions and Variables

Expressions and Variables Expressions and Variables Expressions print(expression) An expression is evaluated to give a value. For example: 2 + 9-6 Evaluates to: 5 Data Types Integers 1, 2, 3, 42, 100, -5 Floating points 2.5, 7.0,

More information

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

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

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

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6 Repetition Statements Animated Version required for reproduction or display. Chapter 6-1 Objectives After you have read and studied this chapter, you should be able to Implement repetition control

More information

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

Topic 3: Fractions. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra Topic : Fractions Topic Integers Topic Decimals Topic Fractions Topic Ratios Topic Percentages Duration / weeks Content Outline PART (/ week) Introduction Converting Fractions to Decimals Converting Decimals

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

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

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

AP Computer Science A. Return values

AP Computer Science A. Return values AP Computer Science A Return values Distance between points Write a method that given x and y coordinates for two points prints the distance between them Pseudocode? Java's Math class Method name Math.abs(value)

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

VBScript: Math Functions

VBScript: Math Functions C h a p t e r 3 VBScript: Math Functions In this chapter, you will learn how to use the following VBScript functions to World Class standards: 1. Writing Math Equations in VBScripts 2. Beginning a New

More information

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

Excerpt from Art of Problem Solving Volume 1: the Basics 2014 AoPS Inc. Chapter 5 Using the Integers In spite of their being a rather restricted class of numbers, the integers have a lot of interesting properties and uses. Math which involves the properties of integers is

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

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

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore CS 115 Data Types and Arithmetic; Testing Taken from notes by Dr. Neil Moore Statements A statement is the smallest unit of code that can be executed on its own. So far we ve seen simple statements: Assignment:

More information

Lecture Notes on Contracts

Lecture Notes on Contracts Lecture Notes on Contracts 15-122: Principles of Imperative Computation Frank Pfenning Lecture 2 August 30, 2012 1 Introduction For an overview the course goals and the mechanics and schedule of the course,

More information

(Subroutines in Visual Basic)

(Subroutines in Visual Basic) Ch 7 Procedures (Subroutines in Visual Basic) Visual Basic Procedures Structured Programs To simplify writing complex programs, most Programmers (Designers/Developers) choose to split the problem into

More information

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

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto CS 170 Java Programming 1 Expressions Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 What is an expression? Expression Vocabulary Any combination of operators and operands which, when

More information

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

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials Fundamentals We build up instructions from three types of materials Constants Expressions Fundamentals Constants are just that, they are values that don t change as our macros are executing Fundamentals

More information

NUMBERS AND NUMBER RELATIONSHIPS

NUMBERS AND NUMBER RELATIONSHIPS MODULE MODULE CHAPTERS Numbers and number patterns 2 Money matters KEY SKILLS writing rational numbers as terminating or recurring decimals identifying between which two integers any irrational number

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2, 2.1-2.2 Copyright 2011 by Pearson Education 2 Method name Math.abs(value) Math.ceil(value) Math.floor(value)

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2, 2.1-2.2 Java's Math class Method name Math.abs(value) Math.ceil(value) Math.floor(value) Description absolute

More information

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

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch Purpose: We will take a look at programming this week using a language called Scratch. Scratch is a programming language that was developed

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Return values, Math, and double reading: 3.2, 2.1-2.2 Copyright 2011 by Pearson Education 2 Java's Math class Method name Math.abs(value) Math.ceil(value) Math.floor(value)

More information

Unit 1 Lesson 4. Introduction to Control Statements

Unit 1 Lesson 4. Introduction to Control Statements Unit 1 Lesson 4 Introduction to Control Statements Essential Question: How are control loops used to alter the execution flow of a program? Lesson 4: Introduction to Control Statements Objectives: Use

More information

FUNctions. Lecture 03 Spring 2018

FUNctions. Lecture 03 Spring 2018 FUNctions Lecture 03 Spring 2018 Announcements PS0 Due Tomorrow at 11:59pm WS1 Released soon, due next Friday 2/2 at 11:59pm Not quite understand a topic in lecture this week? Come to Tutoring Tomorrow

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-2: Return; doubles and casting reading: 3.2, 4.1 videos: Ch. 3 #2 Copyright 2009 by Pearson Education Finish Car example Lecture outline Returns Java Math library

More information

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

>>> * *(25**0.16) *10*(25**0.16) #An Interactive Session in the Python Shell. #When you type a statement in the Python Shell, #the statement is executed immediately. If the #the statement is an expression, its value is #displayed. #Lines

More information

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

Functions and Procedures. Functions. Built In Functions. Built In Functions in VB FIT 100 FIT 100 Functions Functions and Procedures Similarities: Little mini-programs that are named and include a series of code statements (instructions) to be executed when called. Differences: Functions have a specific

More information

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

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2, 2.1-2.2 Method name Math.abs(value) Math.ceil(value) Math.floor(value) Java's Math class Description absolute

More information

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

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18 Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

More information

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

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators 1 Professor: Sana Odeh odeh@courant.nyu.edu Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators Review What s wrong with this line of code? print( He said Hello ) What s wrong with

More information

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

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1 CPE 101 mod/reusing slides from a UW course Overview (4) Lecture 4: Arithmetic Expressions Arithmetic expressions Integer and floating-point (double) types Unary and binary operators Precedence Associativity

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

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

CHAPTER 4: DECIMALS. Image from Microsoft Office Clip Art CHAPTER 4 CONTENTS CHAPTER 4: DECIMALS Image from Microsoft Office Clip Art CHAPTER 4 CONTENTS 4.1 Introduction to Decimals 4.2 Converting between Decimals and Fractions 4.3 Addition and Subtraction of Decimals 4.4 Multiplication

More information

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

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output? Arithmetic Operators Section 2.15 & 3.2 p 60-63, 81-89 1 Today Arithmetic Operators & Expressions o Computation o Precedence o Associativity o Algebra vs C++ o Exponents 2 Assigning floats to ints int

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

Project 3: RPN Calculator

Project 3: RPN Calculator ECE267 @ UIC, Spring 2012, Wenjing Rao Project 3: RPN Calculator What to do: Ask the user to input a string of expression in RPN form (+ - * / ), use a stack to evaluate the result and display the result

More information

UNIT 9A Randomness in Computation: Random Number Generators

UNIT 9A Randomness in Computation: Random Number Generators UNIT 9A Randomness in Computation: Random Number Generators 1 Last Unit Computer organization: what s under the hood 3 This Unit Random number generation Using pseudorandom numbers 4 Overview The concept

More information

5. Selection: If and Switch Controls

5. Selection: If and Switch Controls Computer Science I CS 135 5. Selection: If and Switch Controls René Doursat Department of Computer Science & Engineering University of Nevada, Reno Fall 2005 Computer Science I CS 135 0. Course Presentation

More information

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

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements Topic 4 Variables Once a programmer has understood the use of variables, he has understood the essence of programming -Edsger Dijkstra What we will do today Explain and look at examples of primitive data

More information

Prime Time (Factors and Multiples)

Prime Time (Factors and Multiples) CONFIDENCE LEVEL: Prime Time Knowledge Map for 6 th Grade Math Prime Time (Factors and Multiples). A factor is a whole numbers that is multiplied by another whole number to get a product. (Ex: x 5 = ;

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Arithmetic and Bitwise Operations on Binary Data

Arithmetic and Bitwise Operations on Binary Data Arithmetic and Bitwise Operations on Binary Data CSCI 2400: Computer Architecture ECE 3217: Computer Architecture and Organization Instructor: David Ferry Slides adapted from Bryant & O Hallaron s slides

More information