Advertise here.

Tuesday, 28 August 2012

Pascal Programming Lesson #6 - Loops


Loops are used when you want to repeat code a lot of times. For example, if you wanted to print "Hello" on the screen 10 times you would need 10 Writeln commands. You could do the same thing by putting 1 Writelncommand inside a loop which repeats itself 10 times.

There are 3 types of loops which are the for loop, while loop and repeat until loop.

For loop

The for loop uses a loop counter variable, which it adds 1 to each time, to loop from a first number to a last number.

program Loops;

var
   i: Integer;

begin
   for i := 1 to 10 do
      Writeln('Hello');
end.

If you want to have more than 1 command inside a loop then you must put them between a begin and an end.

program Loops;

var
   i: Integer;

begin
   for i := 1 to 10 do
      begin
         Writeln('Hello');
         Writeln('This is loop ',i);
      end;
end.

While loop

The while loop repeats while a condition is true. The condition is tested at the top of the loop and not at any time while the loop is running as the name suggests. A while loop does not need a loop variable but if you want to use one then you must initialize its value before entering the loop.

program Loops;

var
   i: Integer;

begin
   i := 0;
   while i <= 10
      begin
         i := i + 1;
         Writeln('Hello');
      end;
end.

Repeat until loop

The repeat until loop is like the while loop except that it tests the condition at the bottom of the loop. It also doesn't have to have a begin and an end if it has more than one command inside it.

program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Writeln('Hello');
   until i = 10;
end.

If you want to use more than one condition for either the while or repeat loops then you have to put the conditions between brackets.

program Loops;

var
   i: Integer;
   s: String;

begin
   i := 0;
   repeat
      i := i + 1;
      Write('Enter a number: ');
      Readln(s);
   until (i = 10) or (s = 0);
end.

Break and Continue

The Break command will exit a loop at any time. The following program will not print anything because it exits the loop before it gets there.

program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Break;
      Writeln(i);
   until i = 10;
end.

The Continue command will jump back to the top of a loop. This example will also not print anything but unlike the Break example, it will count all the way to 10.

program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Continue;
      Writeln(i);
   until i = 10;
end.

Pascal Programming Lesson #5 - Decisions


if then else

The if statement allows a program to make a decision based on a condition. The following example asks the user to enter a number and tells you if the number is greater than 5:

program Decisions;

var
   i: Integer;

begin
   Writeln('Enter a number');
   Readln(i);
   if i > 5 then
      Writeln('Greater than 5');
end.

Here is a table of the operators than can be used in conditions:

>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
=Equal to
<>Not equal to

The above example only tells you if the number is greater than 5. If you want it to tell you that it is not greater than 5 then we use else. When you use else you must not put a semi-colon on the end of the command before it.

program Decisions;

var
   i: Integer;

begin
   Writeln('Enter a number');
   Readln(i);
   if i > 5 then
      Writeln('Greater than 5')
   else
      Writeln('Not greater than 5');
end.

If the condition is True then the then part is chosen but if it is False then the else part is chosen. This is because the conditions such as i > 5 is a Boolean equation. You can even assign the result of a Boolean equation to a Boolean variable.

program Decisions;

var
   i: Integer;
   b: Boolean;

begin
   Writeln('Enter a number');
   Readln(i);
   b := i > 5;
end.

If you want to use more than 1 condition then you must put each condition in brackets. To join the conditions you can use either AND or OR. If you use AND then both conditions must be true but if you use OR then only 1 or both of the conditions must be true.

program Decisions;

var
   i: Integer;

begin
   Writeln('Enter a number');
   Readln(i);
   if (i > 1) and (i < 100) then
      Writeln('The number is between 1 and 100');
end.

If you want to put 2 or more commands for an if statement for both the then and the else parts you must usebegin and end; to group them together. You will see that this end has a semi-colon after it instead of a full stop.

program Decisions;

var
   i: Integer;

begin
   Writeln('Enter a number');
   Readln(i);
   if i > 0 then
      begin
         Writeln('You entered ',i);
         Writeln('It is a positive number');
      end;
end.

You can also use if statements inside other if statements.

program Decisions;

var
   i: Integer;

begin
   Writeln('Enter a number');
   Readln(i);
   if i > 0 then
      Writeln('Positive')
   else
      if i < 0 then
         Writeln('Negative')
      else
         Writeln('Zero');
end.

Case

The case command is like an if statement but you can have many conditions with actions for each one.

program Decisions;

uses
   crt;

var
   Choice: Char;

begin
   Writeln('Which on of these do you like?');
   Writeln('a - Apple:');
   Writeln('b - Banana:');
   Writeln('c - Carrot:');
   Choice := ReadKey;
   case Choice of
      'a': Writeln('You like apples');
      'b': Writeln('You like bananas');
      'c': Writeln('You like carrots');
   else
      Writeln('You made an invalid choice');
   end;
end.

Pascal Programming Lesson #4 - String Handling and Conversions


String Handling

You can access a specific character in a string if you put the number of the position of that character in square brackets behind a string.

program Strings;

var
   s: String;
   c: Char;

begin
   s := 'Hello';
   c := s[1];{c = 'H'}
end.

You can get the length of a string using the Length command.

program Strings;

var
   s: String;
   l: Integer;

begin
   s := 'Hello';
   l := Length(s);{l = 5}
end.

To find the position of a string within a string use the Pos command.
Parameters:
1: String to find
2: String to look in

program Strings;

var
   s: String;
   p: Integer;

begin
   s := 'Hello world';
   p := Pos('world',s);
end.

The Delete command removes characters from a string.
Parameters:
1: String to delete characters from
2: Position to start deleting from
3: Amount of characters to delete

program Strings;

var
   s: String;

begin
   s := 'Hello';
   Delete(s,1,1);{s = 'ello'}
end.

The Copy command is like the square brackets but can access more than just one character.
Parameters:
1: String to copy characters from
2: Position to copy from
3: Amount of characters to copy

program Strings;

var
   s, t: String;

begin
   s := 'Hello';
   t := Copy(s,1,3);{t = 'Hel'}
end.

Insert will insert characters into a string at a certain position.
Parameters:
1: String that will be inserted into the other string
2: String that will have characters inserted into it
3: Position to insert characters

program Strings;

var
   s: String;

begin
   s := 'Hlo';
   Insert('el',s,2);
end.

The ParamStr command will give you the command-line parameters that were passed to a program.ParamCount will tell you how many parameters were passed to the program. Parameter 0 is always the program's name and from 1 upwards are the parameters that have been typed by the user.

program Strings;

var
   s: String;
   i: Integer;

begin
   s := ParamStr(0);
   i := ParamCount;
end.

Conversions

The Str command converts an integer to a string.

program Convert;

var
   s: String;
   i: Integer;

begin
   i := 123;
   Str(i,s);
end.

The Val command converts a string to an integer.

program Convert;

var
   s: String;
   i: Integer;
   e: Integer;

begin
   s := '123';
   Val(s,i,e);
end.

Int will give you the number before the comma in a real number.

program Convert;

var
   r: Real;

begin
   r := Int(3.14);
end.

Frac will give you the number after the comma in a real number.

program Convert;

var
   r: Real;

begin
   r := Frac(3.14);
end.

Round will round off a real number to the nearest integer.

program Convert;

var
   i: Integer;

begin
   i := Round(3.14);
end.

Trunc will give you the number before the comma of a real number as an integer.

program Convert;

var
   i: Integer;

begin
   i := Trunc(3.14);
end.

Computers use the numbers 0 to 255(1 byte) to represent characters internally and these are called ASCII characters. The Ord command will convert a character to number and the Chr command will convert a number to a character. Using a # in front of a number will also convert it to a character.

program Convert;

var
   b: Byte;
   c: Char;

begin
   c := 'a';
   b := Ord(c);
   c := Chr(b);
   c := #123;
end.

The UpCase command changes a character from a lowercase letter to and uppercase letter.

program Convert;

var
   c: Char;

begin
   c := 'a';
   c := UpCase(c);
end.

There is no lowercase command but you can do it by adding 32 to the ordinal value of an uppercase letter and then changing it back to a character.

Extras

The Random command will give you a random number from 0 to the number you give it - 1. The Randomcommand generates the same random numbers every time you run a program so the Randomize command is used to make them more random by using the system clock.

program Rand;

var
   i: Integer;

begin
   Randomize;
   i := Random(101);
end.

Pascal Programming Lesson #3 - Variables and Constants


Variables are names given to blocks of the computer's memory. The names are used to store values in these blocks of memory.

Variables can hold values which are either numbers, strings or Boolean. We already know what numbers are. Strings are made up of letters. Boolean variables can have one of two values, either True or False.

Using variables

You must always declare a variable before you use it. We use the var statement to do this. You must also choose what type of variable it is. Here is a table of the different variable types:

Byte0 to 255
Word0 to 65535
ShortInt-128 to 127
Integer-32768 to 32767
LongInt-4228250000 to 4228249000
Realfloating point values
Char1 character
Stringup to 255 characters
Booleantrue or false

Here is an example of how to declare an integer variable named i:

program Variables;

var
   i: Integer;

begin
end.

To assign a value to a variable we use :=.
program Variables;

var
   i: Integer;

begin
   i := 5;
end.

You can create 2 or more variables of the same type if you seperate their names with commas. You can also create variables of a different type without the need for another var statemtent.

program Variables;

var
   i, j: Integer;
   s: String;

begin
end.

When you assign a value to a string variable, you must put it between single quotes. Boolean variables can only be assigned the values True and False.

program Variables;

var
   i: Integer;
   s: String;
   b: Boolean;

begin
   i := -3;
   s := 'Hello';
   b := True;
end.

Calculations with variables

Variables can be used in calculations. For example you could assign the value to a variable and then add the number 1 to it. Here is a table of the operators that can be used:

+Add
-Subtract
*Multiply
/Floating Point Divide
divInteger Divide
modRemainder of Integer Division

The following example shows a few calculations that can be done:

program Variables;

var
   Num1, Num2, Ans: Integer;

begin
   Ans := 1 + 1;
   Num1 := 5;
   Ans := Num1 + 3;
   Num2 := 2;
   Ans := Num1 - Num2;
   Ans := Ans * Num1;
end.

Strings hold characters. Characters include the the letters of the alphabet as well as special characters and even numbers. It is important to understand that integer numbers and string numbers are different things. You can add strings together as well. All that happens is it joins the 2 strings. If you add the strings '1' and '1' you will get '11' and not 2.

program Variables;

var
   s: String;

begin
   s := '1' + '1';
end.

You can read vales from the keyboard into variables using Readln and ReadKey. ReadKey is from the crt unit and only reads 1 character. You will see that ReadKey works differently to Readln

program Variables;

uses crt;

var
   i: Integer;
   s: String;
   c: Char;

begin
   Readln(i);
   Readln(s);
   c := ReadKey;
end.

Printing variables on the screen is just as easy. If you want to print variables and text with the same Writelnthen seperate them with commas.

program Variables;

var
   i: Integer;
   s: String;
begin
   i := 24;
   s := 'Hello';
   Writeln(i);
   Writeln(s,' world');
end.

Constants

Constants are like variables except that their values can't change. You assign a value to a constant when you create it. const is used instead of var when declaring a constant. Constants are used for values that do not change such as the value of pi.

program Variables;

const
   pi: Real = 3.14;

var
   c, d: Real;

begin
   d := 5;
   c := pi * d;
end.

Pascal Programming Lesson #2 - Colors, Coordinates, Windows and Sound


Colors

To change the color of the text printed on the screen we use the TextColor command.

program Colors;

uses
   crt;

begin
   TextColor(Red);
   Writeln('Hello');
   TextColor(White);
   Writeln('world');
end.

The TextBackground command changes the color of the background of text. If you want to change the whole screen to a certain color then you must use ClrScr.

program Colors;

uses
   crt;

begin
   TextBackground(Red);
   Writeln('Hello');
   TextColor(White);
   ClrScr;
end.

Screen coordinates

You can put the cursor anywhere on the screen using the GoToXY command. In DOS, the screen is 80 characters wide and 25 characters high. The height and width varies on other platforms. You may remember graphs from Maths which have a X and a Y axis. Screen coordinates work in a similar way. Here is an example of how to move the cursor to the 10th column in the 5th row.

program Coordinates;

uses
   crt;

begin
   GoToXY(10,5);
   Writeln('Hello');
end.

Windows

Windows let you define a part of the screen that your output will be confined to. If you create a window and clear the screen it will only clear what is in the window. The Window command has 4 parameters which are the top left coordinates and the bottom right coordinates.

program Coordinates;

uses
   crt;

begin
   Window(1,1,10,5);
   TextBackground(Blue);
   ClrScr;
end.

Using window(1,1,80,25) will set the window back to the normal size.

Sound

The Sound command makes a sound at the frequency you give it. It does not stop making a sound until theNoSound command is used. The Delay command pauses a program for the amount of milliseconds you tell it to. Delay is used between Sound and NoSound to make the sound last for a certain amount of time.

program Sounds;

uses
   crt;

begin
   Sound(1000);
   Delay(1000);
   NoSound;
end.

Pascal Programming Lesson #1 - Introduction to Pascal


About Pascal

The Pascal programming language was created by Niklaus Wirth in 1970. It was named after Blaise Pascal, a famous French Mathematician. It was made as a language to teach programming and to be reliable and efficient. Pascal has since become more than just an academic language and is now used commercially.

What you will need

Before you start learning Pascal, you will need a Pascal compiler. This tutorial uses the Free Pascal Compiler. You can find a list of other Pascal compilers at TheFreeCountry's Pascal compiler list.

Your first program

The first thing to do is to either open your IDE if your compiler comes with one or open a text editor.

We always start a program by typing its name. Type program and the name of the program next to it. We will call our first program "Hello" because it is going to print the words "Hello world" on the screen.

program Hello;

Next we will type begin and end. We are going to type the main body of the program between these 2 keywords. Remember to put the full stop after the end.

program Hello;

begin
end.

The Write command prints words on the screen.

program Hello;

begin
   Write('Hello world');
end.

You will see that the "Hello world" is between single quotes. This is because it is what is called a string. All strings must be like this. The semi-colon at the end of the line is a statement separator. You must always remember to put it at the end of the line.

The Readln command will now be used to wait for the user to press enter before ending the program.

program Hello;

begin
   Write('Hello world');
   Readln;
end.

You must now save your program as hello.pas.

Compiling

Our first program is now ready to be compiled. When you compile a program, the compiler reads your source code and turns it into an executable file. If you are using an IDE then pressing CTRL+F9 is usually used to compile and run the program. If you are compiling from the command line with Free Pascal then enter the following:

fpc hello.pas

If you get any errors when you compile it then you must go over this lesson again to find out where you made them. IDE users will find that their programs compile and run at the same time. Command line users must type the name of the program in at the command prompt to run it.

You should see the words "Hello world" when you run your program and pressing enter will exit the program. Congratulations! You have just made your first Pascal program.

More commands

Writeln is just like Write except that it moves the cursor onto the next line after it has printed the words. Here is a program that will print "Hello" and then "world" on the next line:

program Hello;

begin
   Writeln('Hello');
   Write('world');
   Readln;
end.

If you want to skip a line then just use Writeln by itself without any brackets.

Using commands from units

The commands that are built into your Pascal compiler are very basic and we will need a few more. Units can be included in a program to give you access to more commands. The crt unit is one of the most useful. TheClrScr command in the crt unit clears the screen. Here is how you use it:

program Hello;

uses
   crt;

begin
   ClrScr;
   Write('Hello world');
   Readln;
end.

Comments

Comments are things that are used to explain what parts of a program do. Comments are ignored by the compiler and are only there for the people who use the source code. Comments must be put between curly brackets. You should always have a comment at the top of your program to say what it does as well as comments for any code that is difficult to understand. Here is an example of how to comment the program we just made:

{This program will clear the screen, print "Hello world" and wait for the user to press enter.}

program Hello;

uses
   crt;

begin
   ClrScr;{Clears the screen}
   Write('Hello world');{Prints "Hello world"}
   Readln;{Waits for the user to press enter}
end.

Indentation

You will notice that I have put 3 spaces in front of some of the commands. This is called indentation and it is used to make a program easier to read. A lot of beginners do not understand the reason for indentation and don't use it but when we start making longer, more complex programs, you will understand.

VB.NET Programming lesson #4 - String Handling


String handling is the use of various methods to manipulate a string into a form that a program needs it in. You will already know from a previous lesson that a string is a variable that stores text. All programs use text in some way since text is used to show messages to the user and for getting input from the user which makes string handling an important part of programming.

String concatenation

String concatenation means joining 2 strings together. To join 2 strings together you can use either an ampersand (&) or a plus (+). Here is an example that uses the ampersand to join 2 strings together with a space between them.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim string1 As String = "Part one"
      Dim string2 As String = "Part two"
      Dim string3 As String = string1 & " " & string2
      Console.WriteLine(string3)
   End Sub
End Class

You can also use a plus instead of an ampersand.

Dim string3 As String = string1 + " " + string2

String handling commands

Visual Basic.NET has various useful commands for manipulating strings. The following are some of the commands you will use most often.

Upper and lower case

To change all the letters in a string to uppercase letters you can use the ToUpper command. You can use theToLower command to change them all to lowercase letters. Both of these commands and a lot of the others are called on the declared string object which means you use them by putting a dot after the name of the string followed by the command. Here is an example that demonstrates both of the commands.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Some Text"
      Dim lower As String = MyString.ToLower()
      Dim upper As String = MyString.ToUpper()
      Console.WriteLine(lower)
      Console.WriteLine(upper)
   End Sub
End Class


Getting part of a string

You can use the Left command to get a certain number of characters from the left of a string and there is also a Right command that does the same from the right side of a string. Both commands take 2 paramaters. The first parameter is the string to work with and the second parameter is the number of characters to get from the string. Here is an example that takes 4 characters from the left of a string and also 4 characters from the right.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Some Text"
      Dim LeftPart As String = Left(MyString, 4)
      Dim RightPart As String = Right(MyString, 4)
      Console.WriteLine(LeftPart)
      Console.WriteLine(RightPart)
   End Sub
End Class

You can use the Substring command to get part of a string from anywhere in a string. The Substringcommand has 2 parameters which are the position to start copying characters from and then the number of characters to copy. The start position parameter is a bit confusing because the numbering of the positions of a string start at 0 instead of one so you will have to substract 1 from the actual position in a string. So if you want to start from the 5th character in a string you must actually use 4 as the start position. The number of characters parameter does not start at 0 but rather from 1 because it is counting the number of characters to copy. The 2nd parameter is optional and if left out it will just keep going until the end of the string. Here is an example that uses Substring to extract the middle word in a string.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim Fullname As String = "John Paul Smith"
      Dim MiddleName As String = Fullname.Substring(5, 4)
      Console.WriteLine(MiddleName)
   End Sub
End Class


Length of a string

You can get the number of characters in a string using the Length property of a string. The Length property is not a command but a property so you must not use brackets with it. Here is an example that prints out the length of a string.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Some Text"
      Console.WriteLine(MyString.Length)
   End Sub
End Class


Searching a string

You can use the IndexOf command to find out if a string contains another string and at what position the string was found. The IndexOf command acts on a string and takes one parameter which is the string to find. It returns a number which is the position in the string that the string to find was found. The position numbering starts from 0 and not 1 so you need to be careful with it. If the string was not found then -1 is returned. Here is an example that shows how to find a string in another string using the IndexOf command.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "A needle in a haystack"
      Dim FoundPosition As Integer = MyString.IndexOf("needle")
      Console.WriteLine(FoundPosition)
   End Sub
End Class


Replacing parts of a string

You can use the Replace command to replace parts of a string. The command takes 2 parameters. The first parameter is the string to find in the string and the second parameter is the string to replace it with. Here is an example that replaces the word "dogs" with the word "cats".

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "I like dogs"
      Dim NewString As String = MyString.Replace("dogs", "cats")
      Console.WriteLine(NewString)
   End Sub
End Class


Trimming

You can remove any spaces from both the beginning and the end of a string by using the Trim command. This is useful for when you ask a user to enter something because they sometimes add spaces by mistake. Here is an example of how to use it.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = " Some Text "
      Dim NewString As String = MyString.Trim()
      Console.WriteLine(NewString)
   End Sub
End Class


String data type conversions

You often need to convert other data types such as integers to strings before you can output them to the user. For example, if you want to display a message to the user with a number that was calculated in the program then you will have to convert that number to a string and then concatenate it with the message text. TheConvert.ToString command will convert things to a string most of the time. All objects also have a ToStringcommand on them which produces a string representation of the object but this method is not as reliable asConvert.ToString because it sometimes produces unexpected results.

You can convert a string to a lot of other types using the various Convert methods such as Convert.ToInt32 to convert a string to an integer. This kind of thing is useful for when a user enters some text that needs to be converted to an integer before calculations can be done on it.

Here is an example that converts both from a string and to a string. It gets the user to enter 2 numbers and then adds them together and then outputs the result along with a nice message.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Console.WriteLine("Please enter first number:")
      Dim Num1 As String = Console.ReadLine()
      Console.WriteLine("Please enter second number:")
      Dim Num2 As String = Console.ReadLine()
      Dim int1 As Integer = Convert.ToInt32(Num1)
      Dim int2 As Integer = Convert.ToInt32(Num2)
      Dim result As Integer = int1 + int2
      Dim message As String = "The result is " & Convert.ToString(result)
      Console.WriteLine(message)
   End Sub
End Class


Characters and strings

Strings are actually just sequences of characters. If you want to get an individual character within a string all you need to do is put brackets behind the name of the string with the number of the position of the character you want. This position is an index which means it starts at 0 and not at 1. Here is an example that gets the 3rd character (index 2) from a string.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Something"
      Dim MyChar As Char = MyString(2)
      Console.WriteLine(MyChar)
   End Sub
End Class


Escaping characters

Visual Basic.NET uses double quotes around the contents of a string as you already know very well by now. The problem with this is that when you want to put actual double quotes in a string then it thinks that you are closing the string. To get around this problem you need to escape the double quotes by using 2 of them instead of 1. The 2 double quotes will show up as 1 double quote in the program.

Imports Microsoft.VisualBasic
Imports System

Class StringHandling
   Shared Sub Main()
      Dim MyString As String = "Putting ""quotes"" in a string"
      Console.WriteLine(MyString)
   End Sub
End Class


Other string handling commands

There are many more string handling commands that you can use but we have covered the most useful ones. If you are interested in more of them then have a look at Microsoft's String class members reference.


Practice

Write a program that asks the user for their full name. Extract the first name and the last name from the full name entered by the user by using the commands you have learnt in this lesson. Finding the position of the space between the two names will help you solve this problem.

VB.NET Programming lesson #3 - Variables


A variable is something that is used in a program to store data in memory. Variables are used for storing the data that a program is busy working with. Variables can store all sorts of different types of data including things like numbers and text. Variables are important because it is almost impossible to write a useful program that doesn't use them.

Declaring a variable

Here is an example of how to declare a variable followed by an explanation.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer
   End Sub

End Class

The variable is declared using the Dim keyword followed by the name of the variable which in this case isMyInt. After that is the As keyword followed by the data type of the variable which is an Integer in this example. An Integer is a variable that stores numbers. There are different types of variables for storing different types of data which you will learn about later.

Setting the value of a variable

You set the value of a variable using an equals sign (=). Here is an example of how to set the value of a variable.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer
      MyInt = 5
   End Sub

End Class

In the above example the variable called MyInt has been set to the value of 5.

The Console.WriteLine command can be used to display the value of a variable. You must not use double quotes with Console.WriteLine when using a variable like you had to when printing words on the screen because then the compiler thinks you want to print the name of the variable instead of the value it holds. Here is how you print the value of a variable.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer
      MyInt = 5
      Console.WriteLine(MyInt)
   End Sub

End Class

You can set the value of a variable at the same time as you declare it which is called initializing a variable. Here is an example of how to initialize a variable.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer = 7
   End Sub

End Class

You can declare more than one variable by adding another variable name to the same declaration in which case you must separate the variable names using a comma. Another way of doing it is to just declare another variable on a new line which a lot of programmers prefer doing because then the variables can be initialized easily.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt1, MyInt2 As Integer
      Dim MyInt3 As Integer

   End Sub

End Class

Calculations using variables

You can perform calculations on variables using one of the 4 basic operations which are addition, subtraction, multiplication and division. The result of an operation must be stored in a variable otherwise it is lost. Here is an example in which the numbers 2 and 3 are added together and the result is stored in a variable calledMyInt which is printed on the screen.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt As Integer
      MyInt = 2 + 3
      Console.WriteLine(MyInt)
   End Sub

End Class

You can see from the example above that the plus sign (+) is used for adding numbers. Here are the signs for the 4 operations.

+Add
-Subtract
*Multiply
/Divide

You can use variables in calculations just like you can use numbers. Here is an example in which 2 variables are declared and given values and then one is subtracted from the other and the result is stored in a third variable.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyInt1 As Integer = 10
      Dim MyInt2 As Integer = 8
      Dim Result As Integer
      Result = MyInt1 - MyInt2
      Console.WriteLine(Result)
   End Sub

End Class

Data types

So far we have only been using the Integer data type which can store only numbers. If you want to store other types of data then you need to use a different data type.

The String data type is used for storing text. When you set the value of a string to some text you must surround it with double quotes because this tells the compiler that the text between the quotes is some text and not part of the code that the program must run. Here is an example of how to declare a string called MyString and set its value.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyString As String
      MyString = "Some text"
      Console.WriteLine(MyString)
   End Sub

End Class

The Char data type is similar to a String except that you can only store 1 character in it. Most of the time you will use Strings instead of Chars but it is still important to understand how Chars work. Here is an example of how to declare a Char variable called MyChar and set its value to the letter V.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyChar As Char
      MyChar = "V"
      Console.WriteLine(MyChar)
   End Sub

End Class

Integers can only store whole numbers and can't store numbers with a decimal point. To be able to work with numbers with a decimal point you must use the Decimal data type. Here is an example in which the number 10 is divided by 4 which gives a result that has a decimal point and therefore needs to be stored in the Decimal data type.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyDec As Decimal
      MyDec = 10 / 4
      Console.WriteLine(MyDec)
   End Sub

End Class

The Boolean data type is used for storing either the value True or the value False and nothing else. It doesn't seem very useful but you will find later that it actually is. Understanding how Booleans work is very important for helping you understand how certain other things in programming work which you will come across later. Here is an example of how to declare a Boolean variable called MyBool and set its value to True and to False.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Dim MyBool As Boolean
      MyBool = True
      Console.WriteLine(MyBool)
      MyBool = False
      Console.WriteLine(MyBool)
   End Sub

End Class

There are many more data types but the ones you have learnt so far cover the most common things you will come across in VB.NET programming. Your knowledge of the data types you have learnt will be enough to help you figure out how to use any of the other data types.

Storing user input

If you want to get the user to type something in and use it in your program then you can do that by using theConsole.ReadLine command which waits for the user to type some text and press Enter. When the user has pressed Enter the text the user entered is returned by Console.ReadLine so you have to store the value returned by the command in a variable. Here is an example in which the user is asked to type in some text and then the text the user entered is printed out again.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Console.WriteLine("Please enter something:")
      Dim EnteredText As String
      EnteredText = Console.ReadLine()
      Console.WriteLine("You entered:")
      Console.WriteLine(EnteredText)
   End Sub

End Class

Type conversions

You will often have the need to convert variables to other data types. For example the Console.ReadLinecommand only reads in Strings so if you want the user to enter a number you have to convert the String that was read in to an Integer. There are quite a few different ways of converting between data types but you will only learn a few of them right now.

The first way of converting between data types is using a group of commands that start with the letter C. There is a command called CInt for example which is used to convert other data types such as Strings to Integers. Here is an example of how to use it in which the user is asked to enter a value which is stored in a String and then converted to an Integer using CInt and then shown again to the user.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Console.WriteLine("Please enter a number:")
      Dim EnteredText As String
      EnteredText = Console.ReadLine()
      Dim MyInt As Integer
      MyInt = CInt(EnteredText)
      Console.WriteLine("The converted value is:")
      Console.WriteLine(MyInt)
   End Sub

End Class

Here are the most useful C conversion commands:
CInt (Convert to Integer)
CStr (Convert to String)
CChar (Convert to Char)
CDec (Convert to Decimal)
CBool (Convert to Boolean)

Another way to convert between types is to use the commands that begin with Convert.To . The .To is followed by the data type such as Convert.ToString. The command for converting to an Integer in this way isConvert.ToInt32. The advantage of the Convert commands over the C commands is that they are also used in programming languages such as C# which you might want to use one day. Here is an example that is the same as the previous one but using Convert.ToInt32 instead of CInt.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Console.WriteLine("Please enter a number:")
      Dim EnteredText As String
      EnteredText = Console.ReadLine()
      Dim MyInt As Integer
      MyInt = Convert.ToInt32(EnteredText)
      Console.WriteLine("The converted value is:")
      Console.WriteLine(MyInt)
   End Sub

End Class

Here are the most useful Convert commands:
Convert.ToInt32 (Convert to Integer)
Convert.ToString (Convert to String)
Convert.ToChar (Convert to Char)
Convert.ToDecimal (Convert to Decimal)
Convert.ToBoolean (Convert to Boolean)

The CType command can be used for when the data type you want to convert to doesn't have either one of the above conversion methods because it can convert to any type. CType takes 2 parameters which are the value to be converted and then the name of the data type to convert to. Here is the same example from above again but this time it uses CType.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Console.WriteLine("Please enter a number:")
      Dim EnteredText As String
      EnteredText = Console.ReadLine()
      Dim MyInt As Integer
      MyInt = CType(EnteredText, Integer)
      Console.WriteLine("The converted value is:")
      Console.WriteLine(MyInt)
   End Sub

End Class

Constants

A constant is a variable whose value can't be changed. You use a constant when you specifically don't want the value of a variable to change during the execution of your program. Constants can be used for things like the company name of the company which wrote the program because the company name must not change anywhere. All you have to do to declare a constant is change the Dim keyword in the normal variable declaration to Const. The value of the constant must be initialized on the same line as it is declared otherwise you will get a compiler error. Here is an example of how to declare a constant for a company name.

Imports Microsoft.VisualBasic
Imports System

Class Variables

   Shared Sub Main()
      Const CompanyName As String = "ABC Company"
      Console.WriteLine(CompanyName)
   End Sub

End Class

Practice

Write a program that asks the user to enter 2 numbers. The program must then add the 2 numbers together and print out the result. Change the program to work with subtraction, multiplication and division and test them all out. Remember that you will have to convert the user's input to an Integer before it can be used in a calculation.