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

Size: px
Start display at page:

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

Transcription

1 Introduction to 2 VISUAL BASIC 2016 edition second print 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 Chapter String Operations String..... functions Details of.. string functions Comparison of... strings String..... matching 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. Unary operators Do not use \ and Mod with floating-point numbers unless you know what are you doing. 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 "con" & "cent" & "rated" 4 * 3 & 5 * / 2 * \ 2 * 3-35 Mod 3 ^ 3 a a a a ( ) Result

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 Add sugar to the end of the str1 VB.NET statement

7 Exercise 1 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, as seen in the example below: Module Module1 Sub Main() Console.Write("Enter the base of triangle one: ") Dim base1 As Double = Console.ReadLine() Console.Write("Enter the height of triangle one: ") Dim height1 As Double = Console.ReadLine() Console.WriteLine("The area of triangle one is {0}.", base1 * height1 / 2) Console.WriteLine() Console.Write("Enter the base of triangle two: ") Dim base2 As Double = Console.ReadLine() Console.Write("Enter the height of triangle two: ") Dim height2 As Double = Console.ReadLine() Console.WriteLine("The area of triangle two is {0}.", base2 * height2 / 2) Console.ReadLine() End Sub End Module The repeating parts of the code above can be made better using procedures. 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 Give the function a name that describes what the function do. Usually, we name function with a few words in CamelCase, e.g. AreaOfTriangle. If the name is valid for a variable, then it is also valid for a function. Usually the inputs of the function. The list is written in a comma separated list of parameters, or is empty if there is no parameter. 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 in functions. 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.

13 You may find the If Then statements cumbersome to read. In this case, you may use single line If statements: If [condition] Then [statement] (Note: single line If statement is usually bad. The use here is an exception.) Function GetGradeByMark(mark As Double) As String If mark >= 80 Then Return "A" If mark >= 70 Then Return "B" If mark >= 50 Then Return "C" Return "F" End Function Function 13 Parameters, parameter list and arguments 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.

14 14 Introduction to Visual Basic (Part 2) Class Work 1. Consider the following declarations of the functions below: ' Returns the n-th Fibonacci number. Function FibonacciNumber(n As Integer) As Integer ' Returns the area of the triangle with sides a, b and c. Function AreaOfTriangle(a As Double, b As Double, c As Double) As Double ' Returns if both subjects pass. Function IsBothPass(chi As Double, eng As Double) As Boolean Write down the code that calculate the following: 2. (a) (b) (c) (d) If a student passes with 69 marks in Chinese and 49 marks in English. The area of triangle with sides 13, 14 and 15. The square of the 15th Fibonacci number. If a student failed any subject with chi marks in Chinese and eng marks in English. Write down a Function statement for the following. Remember to name the function and parameters properly. (a) A function that finds the perimeter of a rectangle, where the width and the height of the rectangle are given. (b) (c) (d) A function that finds the percentage change, where the original value and the new value are given. A function that check if the student gets a pass in all subjects: Chinese, English and Mathematics. A function that checks if the content of a string is a number, e.g. "12345".

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

16 16 Introduction to Visual Basic (Part 2) Example 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

17 2.3 More about parameters More about parameters 17 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 together with the copy. Changing the value of an argument passed by value inside a procedure is bad for readability, because what the variable actually stores may become different from what its name suggests. 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 (the parameters passed by reference are outputs). 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.

18 18 Introduction to Visual Basic (Part 2) Example: ByRef keyword 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

19 Example: using a sub to swap numbers More about parameters 19 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

20 20 Introduction to Visual Basic (Part 2) Exercise 2 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 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.

21 Chapter 3 Mathematics in VB.NET Mathematics in VB.NET 21 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.Min(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.Truncate(2.3) Math.Truncate(-2.3) Math.Abs(-4) Math.Abs(3) Math.Sign(-5) -1

22 22 Introduction to Visual Basic (Part 2) Mathematical constants 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, Math.Truncate Math.Max, Math.Min Double Double, Single, Integer Note: both inputs must have the same data type. Same as the input Same as the input Math.Abs, Int, Fix Double, Single, Integer Same as the input Math.Sign Double, Single, Integer Integer Appendix: related mathematical symbols VB.NET expression Mathematical expression Math.Max(x, y) max(x, y) Math.Min(x, y) min(x, y) Math.Floor(x) x or [x] Math.Ceiling(x) x Math.Abs(x) x Math.Sign(x) sgn(x)

23 Class Work Mathematics in VB.NET 23 Convert each of the following expressions into a VB.NET statement: Mathematical expression VB.NET statement a = x +1 a = Math.Sqrt(x + 1) r = x 2 + x 3 V = 4 πr 3 [Take π = Math.PI] 3 a = max(x, y 2 1) p = min(0.5, 1 x 2 ) x = a

24 24 Introduction to Visual Basic (Part 2) Exercise 3 1. Write a program that calculates the total surface area of a circular cone. The formula of the total surface area A is A = πr( r 2 + h 2 + 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 function that calculate the area of a triangle by the length of its three sides, namely a, b and c. The formula for the area A is a+b+c A = s(s a)(s b)(s c), where s =. (This is known as Heron s 2 formula.) Then write a program to use the function to calculate the area of a triangle, as shown in the sample below. Enter the length of side 1: 13 Enter the length of side 2: 14 Enter the length of side 3: 15 The area of the triangle is 84 square units.

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

26 26 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, because sources of randomness is limited in computers. A notable web site which use this kind of RNG is In VB.NET, a few PRNGs are provided in the language. We will study one of them: Rnd() and Randomize(), to learn how to use random numbers in programs.

27 4.1 Rnd function Rnd function 27 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

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

29 4.2 Simulating dice Simulating dice 29 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. If you use CInt, remember to put it outside Int. CInt must be done after the rounding-off by Int. Otherwise, CInt itself rounds off the number in a different way. 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 < 0 and < and < 1 and < and < 3 6 and < 4 6 and < and < 1

30 30 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 < 0 and < and < 2 4 and < 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.

31 Class work Random integers in a range 31 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)

32 32 Introduction to Visual Basic (Part 2) Exercise 4 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.

33 Chapter 5 Do Loop Statement Do Loop Statement 33 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).

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

35 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 Learning by examples 35 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

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

37 Example: reversing the digits of an integer 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 Learning by examples 37 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.

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

39 Exit Do and Continue Do 39 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.

40 40 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 num = nextnum score += 1 Loop Console.WriteLine() Console.WriteLine("Your score: {0}", score) Console.ReadLine() End Sub

41 Exit Do and Continue Do 41 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.

42 42 Introduction to Visual Basic (Part 2) Exercise 5 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.

43 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 Write a program that finds the greatest common divisor (GCD) of two integers using Euclidean algorithm. Write a function that returns the first digit of an integer. (If the number is negative, ignore its sign.)

44 44 Introduction to Visual Basic (Part 2) Chapter 6 String Operations In this chapter, we learn about strings and text manipulation in VB.NET. Strings and characters Text is stored in computer programs in the form of strings. A string is a sequence of characters. There are different types of characters, such as letters, digits, punctuation marks, symbols, white spaces, and control characters. How is text stored in computers? Unlike humans, computers do not recognise text by its image or sound. Instead, text is converted into numbers, and computers store the numbers instead. A scheme that maps characters into numbers is called a character set. We also have a concept of character encoding, which tells how text in a particular character set is stored in memory. The concept of character encoding is particularly important for Unicode, which has different character encodings for the same character set. For other character sets, we can simply use these two terms interchangeably. A few common character sets are introduced below: ASCII ASCII, the American Standard Code for Information Interchange, is an old character set which is still significant nowadays. ASCII is still significant because most character sets (including Big5, GBK, and Unicode) are backwards compatible with ASCII. We use the term compatible because these character sets contain an exact copy of the US-ASCII character set. ASCII consists of 128 characters, and each character is assigned a code point. However, only code points 32 to 126 are printable, i.e. used for text. The rest of the characters are called control characters.

45 Here is the list of ASCII printable characters. You are supposed to remember the code point of letters and digits, but not the special symbols. Table 1. ASCII table (printable characters only) (sp) P ` p +1! 1 A Q a q +2 " 2 B R b r +3 # 3 C S c s +4 $ 4 D T d t +5 % 5 E U e u +6 & 6 F V f v +7 ' 7 G W g w +8 ( 8 H X h x +9 ) 9 I Y i y +10 * : J Z j z ; K [ k { +12, < L \ l = M ] m } +14. > N ^ n ~ +15 /? O _ o String Operations 45 For the control characters, only CR (13) and LF (10) are significant in VB.NET. In Windows, the character sequence CR + LF moves the cursor to the next line. In VB.NET, this sequence can be referred as the constant vbcrlf.

46 46 Introduction to Visual Basic (Part 2) Big5 and GBK In the past, different character sets were used to store text in different languages. We used Big5 for traditional Chinese and GBK for simplified Chinese. Unfortunately, with the exception of ASCII, we cannot mix text with different character sets together. Worse still, text at those times was often communicated without specifying a character set, or even specifying a wrong character set. When this happened, the text cannot be read unless the actual character set is selected. If a wrong character set is used to read text, the text appears garbled. See the figure below for an example of selecting a wrong character set. This continues to happen for some web sites today, like the one in the figure. Figure 1. (Left) A web page rendered with a wrong character set. (Right) The same web page after selecting the right character set. Source:

47 Unicode Finally, Unicode is made to encode text in different languages simultaneously with a single system. There are three mainstream character encodings in Unicode, namely UTF-8, UTF-16, and UTF-32. Here is a comparison of the character encodings: Character encoding Size of code unit (bytes) Size of a character (bytes) ASCII 1 1 Big5 1 1 or 2 GBK 1 1 or 2 UTF-8 1 1, 2, 3 or 4 UTF or 4 UTF String Operations 47 Strings in.net platform Strings in.net platform are encoded in UTF-16. In UTF-16, characters with Unicode code point or below are encoded with one code unit (2 bytes), and others are encoded with two code units (4 bytes). If a character is encoded in two code units, then it behaves like two separate characters in VB.NET. In these cases, string functions related to characters, the length of string and position of characters do not work properly. Unfortunately, these special characters include Chinese names and Emojis, which are quite commonly used. See to see a list of Chinese characters and for the list of Emojis. If your application handles text in other languages, then the situation is even more complex because of combining diacritical marks. The concepts involved are too advanced to discuss here.

48 48 Introduction to Visual Basic (Part 2) 6.1 String functions A few essential string functions are listed here. First, we learn a function that returns the length of the string: Function Syntax and Meaning Example Result Len Len(str) Returns the length of the string, i.e. its number of characters. Len("Very good!") Len(" 鄧顯 ") 10 2 Next, a few functions that extract a part of a string are introduced: Function Syntax and Meaning Example Result Left Right Mid Trim Left(str, Length) Returns a specified number of characters from the left of the string. Right(str, Length) Returns a specified number of characters from the right of the string. Mid(str, Start) Mid(str, Start, Length) Returns a specified number of characters from a string. If Length is not supplied, all characters from position Start is returned. Trim(str) Removes white space characters at the beginning and at the end of a string. Left("Wonder", 3) Right("Wonder", 2) Mid("Block", 2, 3) Mid("clever", 3) "Won" "er" "loc" "ever" Trim(" I win! ") "I win! Then, we learn functions that do transformations on a string: Function Syntax and Meaning Example Result UCase UCase(str) Converts a string to upper case. UCase("good!") "GOOD!" LCase LCase(str) Converts a string to lower case. LCase("sMaRt") "smart"

49 String functions 49 Next, we have functions that convert characters to and from their Unicode code point: Function Syntax and Meaning Example Result AscW ChrW AscW(str) Returns the Unicode code point of the first character of the string. ChrW(charCode) Returns the character with the given Unicode code point. AscW("A") 65 ChrW(65) "A" Finally, we have functions that search for a string within another string: Function Syntax and Meaning Example Result String.StartsWith [str1].startswith(str2) Returns True if str1 starts with str2, False otherwise. "example".startswith("ex") "example".startswith("ple") True False String.EndsWith [str1].endswith(str2) Returns True if str1 ends with str2, False otherwise. "example".endswith("ex") "example".endswith("ple") False True InStr InStr(Start, Str1, Str2) InStr(Str1, Str2) Returns an integer which is the start position of the first occurrence of Str2 within Str1. Returns zero if Str2 is not found. InStr("aabc", "ab") InStr("abc", "d") InStr(1,"rear","r") InStr(2,"rear","r")

50 50 Introduction to Visual Basic (Part 2) 6.2 Details of string functions In this section, we discuss the details of functions Len, Left, Right, Mid, Trim, AscW and ChrW. String matching will be discussed in another section. In some string functions, there are boundary cases that need to be discussed. A boundary case is a special case that one or more input is at or just beyond its maximum or minimum limits. For example, if the valid mark is from 0 to 100, we consider -1, -0.1, 0, 100, and 101 as the boundary cases. If you intend to write a real application, use string functions that work properly in Unicode. In the functions discussed here, only UCase and LCase work properly. Len function Len function means to return the number of characters in the string. An empty string ( "" ) has a length of 0. Here is an example: Dim TestString As String = "Hello World" Dim TestLength As Integer = Len(TestString) ' Returns 11.

51 Left and Right functions Details of string functions 51 Left and Right extract the specified number of characters from the left and right of the given string respectively. Some special cases are described here: Condition Length length of string Left / Right returns Returns the whole string. Length = 0 Returns an empty string (""). Length < 0 Exception. Results in runtime error if not handled. It does not make sense to pass a negative length to string functions. However, if you pass a variable as the length, you need to check for unexpected cases. Exception handling is not included in this book. Anyway, exceptions in string functions are not meant to be handled. Here is an example: Dim TestString As String = "Hello World!" Dim result As String result = Left(TestString, 5) ' Returns "Hello". result = Left(TestString, 100) ' Returns "Hello World!". result = Left(TestString, 0) ' Returns "". result = Right(TestString, 5) ' Returns "orld!". result = Right(TestString, 100) ' Returns "Hello World!". result = Right(TestString, 0) ' Returns "".

52 52 Introduction to Visual Basic (Part 2) Mid function Mid function extracts the specified number of characters beginning from the given starting position. The position is one-based, i.e. the first character of a string has a position of 1. Some special cases are described here: Condition Length is not specified Start = 1 Mid returns Returns everything starting from the given position. Return is same as Left. Start > length of string Returns an empty string (""). Start 0 or Length < 0 Here is an example: Dim TestString As String = "Mid Function Demo" Dim result As String Exception. Results in runtime error if not handled. result = Mid(TestString, 1, 3) ' Returns "Mid". result = Mid(TestString, 14, 4) ' Returns "Demo". result = Mid(TestString, 5) ' Returns "Function Demo".

53 Trim function Details of string functions 53 Trim function removes white spaces in the beginning and the end of the string. This is used for sanitising user inputs because users may add unneeded spaces to the input. The spaces at the middle of the strings are not removed. However, we should note that white space in this function also includes ideographic space (code point 12288), which is commonly used in CJK (Chinese, Japanese and Korean) text. Dim TestString As String = " Visual Basic " ' Returns "Visual Basic". Dim result As String = Trim(TestString) If you want to remove white spaces at the beginning of the string only, use LTrim. For the end of the string, use RTrim. UCase and LCase functions UCase and LCase functions convert all letters in the strings to upper case and lower case respectively. Other characters, such as digits, are not affected. In addition to a to z, a lot of characters have an upper case or a lower case variant. For example, the upper case variant of the symbol π is Π. Dim TestString As String = "Hello World 1234!" Dim result As String result = UCase(TestString) ' Returns "HELLO WORLD 1234!". result = LCase(TestString) ' Returns "hello world 1234!". Beware of UCase("i") and LCase("I"). In Turkish, they evaluate to "İ" and "ı" respectively.

54 54 Introduction to Visual Basic (Part 2) AscW and ChrW functions AscW returns the Unicode code point of the first character of the string. And ChrW returns a character corresponding to the Unicode code point. However, these functions work only if the character has a Unicode code point of or below. Dim code As Integer code = AscW("A") ' Returns 65. code = AscW("Apple") ' Returns 65. code = AscW("a") ' Returns 97. code = AscW("0") ' Returns 48. code = AscW(vbCrLf) ' Returns 13. Dim character As String character = ChrW(65) ' Returns "A". character = ChrW(97) ' Returns "a". character = ChrW(51) ' Returns "3". character = ChrW(33) ' Returns "!". Class Work Evaluate the following VB.NET expressions. In this exercise, UCase and LCase are executed in American English. VB.NET expression Right("S.2", 1) & Left("Cactus", 1) UCase(LCase("TeStInG")) Len(Mid(Trim(" very good "), 7, 4)) AscW("E") ChrW(AscW("Z") + 20) AscW(UCase("basic")) AscW(Mid(vbCrLf, 2)) Result

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

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

More information

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016 Introduction to 2A VISUAL BASIC 2016 edition Copyright HKTA Tang Hin Memorial Secondary School 2016 Table of Contents. Chapter....... 1.... String...... Operations.........................................

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

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

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

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

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

St. Benedict s High School. Computing Science. Software Design & Development. (Part 1 Computer Programming) National 5

St. Benedict s High School. Computing Science. Software Design & Development. (Part 1 Computer Programming) National 5 Computing Science Software Design & Development (Part 1 Computer Programming) National 5 VARIABLES & DATA TYPES Variables provide temporary storage for information that will be needed while a program is

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

EASY

EASY Downloaded from: justpaste.it/hsfm ------------------------------- EASY ------------------------------- NUMBERS Even or Odd Write a program that accepts a number and returns whether the number is equal

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

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

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

Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017

Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017 Expressions in JavaScript Jerry Cain CS 106AJ October 2, 2017 What is JavaScript? JavaScript was developed at the Netscape Communications Corporation in 1995, reportedly by a single programmer in just

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

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

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

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

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

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

Language Fundamental of VB.NET Part 1. Heng Sovannarith

Language Fundamental of VB.NET Part 1. Heng Sovannarith Language Fundamental of VB.NET Part 1 Heng Sovannarith heng_sovannarith@yahoo.com Variables Declaring Variables Variables are named storage areas inside computer memory where a program places data during

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

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

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

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

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

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

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

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

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

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

VISUAL BASIC 6.0 OVERVIEW

VISUAL BASIC 6.0 OVERVIEW VISUAL BASIC 6.0 OVERVIEW GENERAL CONCEPTS Visual Basic is a visual programming language. You create forms and controls by drawing on the screen rather than by coding as in traditional languages. Visual

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

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

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

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

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

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

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES Chapter 1 : Examples of commonly used formulas - Office Support A collection of useful Excel formulas for sums and counts, dates and times, text manipularion, conditional formatting, percentages, Excel

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

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

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

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

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

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

\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

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

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

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

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

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

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

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

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

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

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

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

JavaScript Basics. The Big Picture

JavaScript Basics. The Big Picture JavaScript Basics At this point, you should have reached a certain comfort level with typing and running JavaScript code assuming, of course, that someone has already written it for you This handout aims

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

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

1/11/2010 Topic 2: Introduction to Programming 1 1

1/11/2010 Topic 2: Introduction to Programming 1 1 Topic 2: Introduction to Programming g 1 1 Recommended Readings Chapter 2 2 2 Computer Programming Gain necessary knowledge of the problem domain Analyze the problem, breaking it into pieces Repeat as

More information

Bits, Words, and Integers

Bits, Words, and Integers Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are

More information

Section 2: Introduction to Java. Historical note

Section 2: Introduction to Java. Historical note The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence

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

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Working with Strings. Husni. The Practice of Computing Using Python, Punch & Enbody, Copyright 2013 Pearson Education, Inc. Working with Strings Husni "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc. Sequence of characters We've talked about strings being a sequence of characters.

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

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

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

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

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Numbers and Computers. Debdeep Mukhopadhyay Assistant Professor Dept of Computer Sc and Engg IIT Madras

Numbers and Computers. Debdeep Mukhopadhyay Assistant Professor Dept of Computer Sc and Engg IIT Madras Numbers and Computers Debdeep Mukhopadhyay Assistant Professor Dept of Computer Sc and Engg IIT Madras 1 Think of a number between 1 and 15 8 9 10 11 12 13 14 15 4 5 6 7 12 13 14 15 2 3 6 7 10 11 14 15

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

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Sequence of Characters. Non-printing Characters. And Then There Is   Subset of UTF-8. String Representation 6/5/2018. Chapter 4 Working with Strings Sequence of Characters we've talked about strings being a sequence of characters. a string is indicated between ' ' or " " the exact sequence of characters is maintained

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

Simple Java Programming Constructs 4

Simple Java Programming Constructs 4 Simple Java Programming Constructs 4 Course Map In this module you will learn the basic Java programming constructs, the if and while statements. Introduction Computer Principles and Components Software

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

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

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

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Princess Nourah bint Abdulrahman University. Computer Sciences Department Princess Nourah bint Abdulrahman University 1 And use http://www.w3schools.com/ JavaScript Objectives Introduction to JavaScript Objects Data Variables Operators Types Functions Events 4 Why Study JavaScript?

More information

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. Numbers & Number Systems

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. Numbers & Number Systems SCHOOL OF ENGINEERING & BUILT ENVIRONMENT Mathematics Numbers & Number Systems Introduction Numbers and Their Properties Multiples and Factors The Division Algorithm Prime and Composite Numbers Prime Factors

More information

Chapter 2.6: Testing and running a solution

Chapter 2.6: Testing and running a solution Chapter 2.6: Testing and running a solution 2.6 (a) Types of Programming Errors When programs are being written it is not surprising that mistakes are made, after all they are very complicated. There are

More information

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Building Java Programs. Chapter 2: Primitive Data and Definite Loops Building Java Programs Chapter 2: Primitive Data and Definite Loops Copyright 2008 2006 by Pearson Education 1 Lecture outline data concepts Primitive types: int, double, char (for now) Expressions: operators,

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals INTERNET PROTOCOLS AND CLIENT-SERVER PROGRAMMING Client SWE344 request Internet response Fall Semester 2008-2009 (081) Server Module 2.1: C# Programming Essentials (Part 1) Dr. El-Sayed El-Alfy Computer

More information

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

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types Managing Data Unit 4 Managing Data Introduction Lesson 4.1 Data types We come across many types of information and data in our daily life. For example, we need to handle data such as name, address, money,

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

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

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

Declaration and Memory

Declaration and Memory Declaration and Memory With the declaration int width; the compiler will set aside a 4-byte (32-bit) block of memory (see right) The compiler has a symbol table, which will have an entry such as Identifier

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

More information