Programming Guide With Visual Studio
Programming Guide With Visual Studio
This is a guide started in 2011 by Mr Gristwood, It is a work in progress, so if a section is not finished
yet, and you think you can add some information to it. Please feel free to mail it to me and I will add
it.
Contents
Introduction to programming. ................................................................................................................ 3
Your First Program (Writeline and Readline) .......................................................................................... 3
All about Variables .................................................................................................................................. 4
Declaring a variable in VB ................................................................................................................... 4
Getting a value into a variable: ........................................................................................................... 4
Using a variable in a program ............................................................................................................. 4
Printing out a variable ......................................................................................................................... 5
Exercises .............................................................................................................................................. 5
Commenting Code .................................................................................................................................. 5
The Selection statements (If and Select) ................................................................................................ 7
The If Statement ................................................................................................................................. 7
If Statement Excercises ....................................................................................................................... 7
The Case Statement ............................................................................................................................ 9
Case, What Else? ................................................................................................................................. 9
Case Sensitive Case’s?....................................................................................................................... 10
Case Statement Exercises ................................................................................................................. 10
The Repetition Statements ................................................................................................................... 11
The FOR loop ..................................................................................................................................... 11
Exercises ............................................................................................................................................ 11
The WHILE loop ................................................................................................................................. 11
Exercises ............................................................................................................................................ 12
Arrays .................................................................................................................................................... 12
Using the array .................................................................................................................................. 13
Arrays and for Loops, your new best friend ..................................................................................... 13
Array exercises .................................................................................................................................. 14
String Theory – EXAMPLES TO BE ADDED, MORE TO BE DONE ............................................................ 14
String Compare ................................................................................................................................. 14
Console.Writeline()
Console.Readline()
The best way to remember these things is, writeline displays something to the screen, readline takes
information from the screen. Now is your turn to try it.
Try typing this code into a Visual Studio Console application and see what happens.
EXERCISE
1. Using the console writeline and console readline ask the user a number of questions that
they have to respond to. Make sure you save this program as “myquestions” as we will use
this later.
Variables are useful when it comes to storing information. It’s fine being able to read from the
screen and display information to it. But once we have asked the user for information, we need a
place to store it so we can use it later.
Variables are called variables because they can be changed at any time during the program.
Variables are declared using the DIM keyword.
Declaring a variable in VB
In this example the blue words are Keywords and must be typed correctly. We have used “number”
as the name for our variable. It is IMPORTANT that you give all your variables a DECENT name
otherwise you will forget what they are for when making bigger programs. Spaces are not allowed in
names of variables so capitalisation can help. E.g. MyVariable makes it easy to read.
I’ve just above two ways of getting a value into a variable. The first way is allocating a value through
the program. If I were to do this with a string(see below) then you would need to use the quotes
(e.g. String = “Mr Gristwood”). The first few examples that you will make will require you to allocate
values via the console.readline as covered in the previous lesson. This is a way of placing whatever is
typed on the screen into a value that we can save and use for later.
Once we have allocated values to a program we then need to use and manipulate them. This is
where you start to use things you have learned in maths and algebra to change the value in them
e.g.
In this example we are adding together number and number 1 to place the value into the variable
‘answer’. So what is the value of Answer now?
As you can see the words in quotes are written words that we want to display to the screen, the
word ‘Number’ is the variable we want to print. In order to link these 2 values together we have to
use the & sign.
Now, the example above shows how to work a variable with an Integer. There are a number of
different data types that can be used for variables so that you can store different information:
These are the basic data types however there are MORE TO BE ADDED
Exercises
1. Modify the program in exercise 1 so that it accepts a number of questions and places them
into variables. At the end of the program, print out each of the answers to the screen
2. Make a program that accepts 3 numbers from a console.readline() adds them all together
and then displays the numbers the person has typed in and the final answer.
3. Modify the program further so that it asks for a person’s name and their two favourite
numbers and displays their name and the numbers they have given and what the answer is
when MULTIPLIED
Commenting Code
Commenting is probably one of the most important things that you can learn to do and will really
affect your final grades when programming. Commenting is a way of adding annotations to your
code. Commenting has a number of benefits:
If your code is broken and you have commented it as you go along, it’s easier to find the places
where the mistakes are and rectify them quick.
If you leave your code for a period of time(e.g. when you go on work experience/term holiday)
when you come back to it and have commented your code, you will get back into it much
quicker
If someone who has never seen your code before looks at it, they will pick up what has been
going on quickly and can give you a higher mark or be able to help/improve your code.
So commenting, easy right? Like everything in life there is a right and wrong way of commenting the
code. Below is two examples of good and bad code.
The skill is learning when to comment, ask yourself, can you explain 3 lines of code with one
comment? If so DO IT. After reading this section of the help guide, every piece of code you make
should be commented.
The If Statement
If statements are one of the most powerful statements that you can learn. These are REALLY useful
as they are known as selection statements. They are used in programs in order to make a decision
for you. We use IF statements in everyday life, but when we process them they seem slightly
different: IF StillHungry THEN GetMoreFood.
This is an example:
This is the basic selection statement, If the number is less than 6 then print the word “hello”. Now
this is a simple statement, that allows you to make a simple choice. In the cup of tea example, If you
want sugar, add sugar, otherwise move on.
If statements can also be extended to include the ELSE statement, this makes them more interesting.
This allows someone to make a choice or decision. If there are only 2 options(e.g. yes, no), then an
else statement can be useful. The final version of the IF statement is the ELSEIF statement. ELSEIF
can work better if you have multiple options and you want to accept a number of different answers.
An example of this is shown below:
If Statement Excercises
Write a program that asks the user for their Password, IF their password is equal to “password”
then let then print the message “welcome to the world”, otherwise print “Access Denied”
Modify your existing program that asks for the user’s 2 favorite numbers. Then ask the user for
what they want to do with those numbers ( +, -, *, /) then perform that operation using IF
Statements
The case statement is another form of Selection statement. It is best used when you have multiple
options and you want to select one based on a condition. An example of a case statement is shown
below:
In this example I have an option number, and depending on the choice the user selects then it will
display the number in words. This works out as a lot less typing than an IF/ELSE statement.
In this example, there is 2 computing teachers and 2 ICT teachers at A-Level. If you type in any of
their names, then it will display an appropriate message, otherwise, tell students to go and learn of
these teachers. You can see the different structures of the case statement; A Case statement that
has 2 possible values that can display the same message and the ‘CASE ELSE’ statement which is for
incorrect values.
Every selection statement should have an option for if the user enters an incorrect value.
This will turn the entire variable ‘myname’ into lower case, making it easier to find the answer.
2. Write a menu system that asks the user to pick from a list of foods. If the user picks a healthy
options display a positive message, otherwise display a negative message.
3. Modify this so that you ask someone who picks a healthy option if they want mayo, if they pick
mayo display “ohhh, you were so close to being healthy” or something like this.
At the moment, FOR loops can seem pretty pointless, but when combined with Arrays later on (see
the relevant chapter for examples)
Exercises
Write a simple For Loop that asks how many times they would like to display a certain
message on entering this number the program then prints out the message that many times.
Make a variable that has a number in it. Give the user 10 guesses to pick the correct number,
if the number is guessed correctly then exit the for loop and display either a congratulations
statement or a commiseration statement. (You will need to use a FOR loop and a number of
IF Statements as well as the EXITFOR command)
While loops are probably the more useful of the repetition statements, however can be more
complicated than FOR loops because of it. While loops are designed to loop until a condition is met,
this can be anything, while a variable is not equal to a word, while something is less than something
else. This makes them extremely powerful and if you understand the syntax of IF statements you
should be able to work these out. An Example of a simple while loop is shown below:
There is another kind of while loop, which is the Do…Until Loop. This works almost the same way as
the while loop but it allows you to enter the loop before you check for the condition to keep looping.
You can see in this case I have not had to initialise the string, as we only test to see if the answer is
right after we have accepted the value for it. The ‘until’ statement can be quite a useful alternative
to the while statement as it does exactly the same thing, but is worded slightly differently and some
people find it easier to understand. If I were to rewrite the above statement with a while statement
is would read:
Exercises
1. Prompt the user to enter their password, you then have to Check their password against the one
in the system. If their password is correct display “Welcome to the world” Otherwise continue to
prompt for a password. For an extra challenge IF the user enters wrong 3 times, display “you are
banished!” and quit (EXIT WHILE)
2. Suppose you had a credit card, with a balance of £50 owed on it. The bank charges you 2%
interest every month. How many months could you leave it, before the bank charges you £100
3. Write a menu system that asks the user to pick from a list of foods. If the user picks a healthy
options display a positive message, otherwise display a negative message. You must continue to
display the menu until someone enters a quit command (e.g. press ‘q’ to quit the program)
Arrays
Arrays are a really important thing when it comes to programming. Arrays are a way of making lots
of variables of the same type all at once. The proper definition of an array is a “collection of like-
minded data”. What happens is that when you declare an array, you specify how many variables
Now, as you can see from my comments, this is an array of 6? How does that work? When you
declare an array, numbers always start from 0, not 1 which means you get an array of 6, not 5. As
you can see this one is of the data type ‘string’ which means I can store up to 6 sports in this one
variable.
What I have done is allocate a value to each point in the array, so then when I want to print out a
particular value in the array, all I do is:
As we have said before, the third location is number “2” as all arrays start at 0.
n.b. there is nothing to stop you allocating values in your array starting at 1, but when you declare an
array the computer will always make a space at 0
Earlier we discussed how to use a for loop and how it is very useful for counting things. Once we
start using arrays, it suddenly becomes VERY useful as we now have a quick and efficient way of
working our way through an array with very little code.
Say we want to get the user to type in 5 pieces of information, we would normally have to do
something like this:
The for loop will cycle through the array adding one to the value of counter each time, which will fill
up the array straight away.
Array exercises
1. Use a Loop (While, FOR) to read in up to 10 variables into an Array, Stopping when a .(full stop)
Is placed in.
2. Write a program that reads 10 numbers entered by the user reports if any of them match
3. Write a program that reads in 10 numbers and prints them out in alphabetical order
Ok, so by this point you should be familiar with using the ‘String’ data type and should be using it for
a lot of your programs. Now the string function is good, but there are other benefits too. There is a
whole raft of ‘specialist’ commands that you can use with string variables that can make strings
REALLY powerful. There is a full list of all the string functions available in Appendix 1, but I’m going
to show you some of the more interesting examples and how they work below.
String Compare
String compare is a really useful function. Now, if we want to compare two values you can use an IF
statement using the ‘=’ command
1) Your Task is to make a form application that takes in a word and returns an answer telling
you if it is a palindrome or not. Use the string functions document in order to work out how
to do this.
2) For an extra challenge, you could try and use string functions to account for capital letters
and spaces. E.g. Take out the capitals and spaces and say if it is still a palindrome.
Sub procedures and functions are 2 words that really mean the same thing. They are a way of
breaking down a program into smaller, more manageable chunks. There are a couple of reasons to
do this:
When you are programming, if you program small bits at a time, it’s easier as you are focusing on
just getting one bit of the code working and not all of it
Sub Procedures can be used over and over again, so if you have a part of your code that you use all
the time but are just changing one, maybe two things, then you should be thinking about using a
sub-procedure/function. When you use a sub it is a bit like making a new mini program on your
page:
How it works
Sub Procedures (subs) are the easier of the 2. A sub can have values sent to it(parameters), but it
cannot return values. This is important to realize early on, as the only difference between a Sub and
a Function is that the Function can return values back to the program above it.
This example passes the name of the person as a parameter to the sub procedure then displays it
using the ‘Display’ sub, when it has executed all the commands in ‘Display’ it then returns back to
main and finishes the program.
This example shows how 2 parameters are passed to the function, the function then adds them up
and returns the answer. The answer is then displayed on the screen. The point to note here is the
‘RETURN’. This is the key difference between a sub and a function, functions can return values. This
is not a very useful function, but if I extended it so that it did ANY mathematical operation, by
sending it the 2 numbers and the operator, then it becomes useful.
Extra Points
As you can see above, I’ve also declared a variable inside the function. This is efficient programming
as when the function finishes, all the variables declared in that function ‘die’, this frees up space in
memory.
Global Variables are different. If you declare a variable at the very top of the program, then it exists
all the way through the program.
This is the global variable example, you can see that ‘Answer’ is declared outside of Main, this means
it is changed in the function Maths so when it goes back to main answer changes there too.
Display the current enrolment statistics displaying the total number of students, the
percentage of male students, the percentage of female students and the split between
local/non-local students. Your program will accept numbers of students and display
percentages. Use functions/sub procedures where necessary.
Accepting input from the keyboard, enroll a student ensuring that your sub/function accepts
all the necessary data to maintain enrollment statistics.
Files require extra ‘plugins’ to make them work with visual basic, it also requires the understanding
of various different commands. When we talk about plugins in programming, we call these Libraries.
The one we need for files to work is called the System Library and it goes at the very top of your
program, right before everything else.
Once we have this library, we can then start to work with files. There are a number of new
commands here and we will work through each individually before showing a full working
program.
Filestream
Filestream is the command that allows you to open a file. This indicates the file you want to open
and how you want to open it. Below is an example of the filestream command, but I’ve put around it
all the possible options you can have with it. Use of Variable to control
file access
Read
Readwrite
This tells me what I want to do with the file Write
Create New – creates a new file with the name of the file in the locaation
Create – creates a new file or if one exists, delete it and start again
Open – Open an existing file
OpenorCreate – Open an existing file, if one doesn’t exist, create it.
Append – Open the existing file and find the end of it.
This looks pretty complicated, but it’s not. I’ve just tried to show all the different options you have
for the 3 different sections of the filestream command. As you have noticed, I’ve declared it just as I
would a normal variable.
You can see that I have declared streamwriter as ‘s’(your variable name will be better!) and
pointed it to the filestream I want to open. Streamwriter allows you to pass information to the
file:
Streamreader is slightly different, this needs a special command called ‘peek’ in order to read from
the file:
The ‘while’ loop will read from the file until the peek command hits the end of the file. In this
example I’m using a writeline to display it to the screen, but you could easily read the values into a
variable then you can find different parts of the file or change information then write it back to
the file later.
One last thing: Whenever you open a streamreader or streamwriter you need to make sure that
you close it. You can see in the last example. There is a command d.close() which shows you how
to close the streamreader or streamwriter class.
Exercises
Write a program that writes your name to a text file (use the program to create the file).
Look at the text file after the program is run, make sure that the files is created and
saved in an appropriate place. Modify the program to read your name back from the file
within the program to make sure it works.
Write a program that gives and takes advice on how to write a program. The program
should open by displaying a piece of advice to the screen. It should then ask the user to
type in a different piece of advice. The next user of the program receives the advice that
was typed in the last time the program was run. Be sure that the first person to run the
program gets some advice.
The organisation Very Best Visual Basic Beginners Becoming Better has declared “B” to
be a dirty letter and has hired you to write a program to eliminate this letter from text
files. Write a program that replaces all occurrences of the letter “B” in a text file with the
letter “X” the program should replace both upper and lowercase letters, “b” and ‘b’, with
‘X’
So up until now we have been working with what is called a console application. This means that
when you run the program a box will show up on the screen that runs your program and all the
program will be text based (e.g. ask a question, get an answer).
This is the simplest form of Form Programming. Run your program, when something happens,
display a messagebox to the screen. This is done using the Messagebox.show command.
All the messagebox does, is show a command to the screen. It is only there to deliver a message.
Mine is ‘hello world’ but it can be anything. This could be useful to display the answer to a
mathematical problem to the screen or just to say, ‘this is going to end the program’
Exam Tip: When coding for assignments there are 2 ways to come to a solution: one that works and
one that works efficiently. The first will give you the bottom mark bands, the second will get you the
higher band. Sometimes it is good to get the code working then try to make it efficient, but this will
take you time, thinking about how to make it efficient in the first place is always the best way to go.
Symbol Meaning
> Greater Than
< Less than
>= Greater Than or Equal to
<= Less Than or Equal to
<> Not Equal to
AND Used for combining different condition
statements e.g. IF <condition> AND <condition>
THEN
OR Used for combining different condition
statements e.g. IF <condition> AND <condition>
THEN
Is, IsNot
Like
TypeOf...Is To check if the data entered is of the right data
type e.g. string, integer
Operator Precedence in Visual Studio (For doing Mathematics)
Exponentiation (^)
Unary identity and negation (+, –)
Multiplication and floating-point division This will give both whole number and
(*, /) remainder
Integer division (\) This will give the whole number of a division
Modulus arithmetic (Mod) MOD will give the remainder of a division
Addition and subtraction (+, –), string
concatenation (+)
String concatenation (&) This will place 2 strings together e.g. (“hello ” &
“world” = “Hello World”
Arithmetic bit shift (<<, >>)
Below is a list of all the string functions that are available in VB.Net.
Function Use
Asc() Returns the character code of the first character of a
string.
Asc("A") returns 65.
Chr() Returns the display character of a character code.
Chr(65) . returns "A"
GetChar() Returns the character at a specified position in a
string, counting from 1.