Visual Basic (VB.NET) – Full Course for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this beginner's course will help you learn the fundamentals of programming with visualbasic.net visual basic is an object-oriented programming language developed by microsoft it's often used to make desktop apps for windows but you can use the programming language for a wide variety of applications and not just on windows kevin drum teaches this course kevin is the head of computer science at a school in the uk kevin will teach you everything from getting visual studio set up for programming to understanding the basic constructs of high-level programming languages this is an excellent course for anyone who wants to learn visual basic leave a comment with the most interesting thing you learned in this course in this series of videos i'm going to introduce you to programming with visual basic.net inside visual studio so let's begin by launching visual studio and taking a look at some of the features exactly what you see here will depend on which version of visual studio you're using you can see that i'm using visual studio 2019 but essentially the features will be the same you can see i have a list of my most recently used projects on the left hand side on the right i'm going to choose the option to create a new project and again what you see next will depend on which version of visual studio you're using it will also depend on which programming languages you installed you can see that i've installed a number of different programming languages which tells you visual studio itself is not a programming language it's an environment in which you can use a programming language i'm going to use visual basic on the right hand side i can see a number of different project templates which i can choose from and i'm going to create a windows forms app so with the correct option chosen click next you're now invited to give the project a name it's offering me the name windows app2 this is because it's the second application which i've created it's not a very meaningful name so i strongly recommend that you change that perhaps perhaps not i think that's been done before that'll do for now you also need to be mindful of where the project will be saved the location of your project you can see the location of mine will be d visual studio 2019 projects but you can change this in fact i'll show you later that once you're in visual studio you can change the default location this is particularly important if you're working in a school or a college or an organization it may be that you only have permission to save visual studio projects in particular locations notice there's a browse button here if you do want to change the location my solution has the same name as the project i'll say a little bit about the difference between a solution and a project in a moment and i'm going to say that i want to place the solution and the project in the same directory by ticking this box since this is a brand new project i'm not going to worry too much about which version of the net framework i'm using more about that later as well so let's hit create and here is visual studio i can see a little message on the bottom right there telling me that there's a new version of visual studio which can be downloaded i'll maybe do that a little bit later i'll just ignore it for now now there are lots of options here which i'll be talking about as we go along but suffice to say for now we have a menu of options across the top and each of these has a number of sub options which in turn might have a number of sub options there's a toolbar i can add extra toolbars which you'll see later but the most useful one is here to start with on the right hand side i can see my solution explorer a solution is a collection of files that make up my application and we'll take a closer look at these files later i have a properties window which will become important when i start building my user interface and on the left hand side there's a toolbox if i just click on this it will move into view if i click away from it it disappears i actually like the toolbox in place all the time so i'm going to click on this little drawing pin to keep it there and i can resize it if i need to in the middle i've got my form this is where i'm going to start building my user interface so let's write some code i'm going to start by dropping a button onto the form so from my toolbox i click on button draw the button onto the form because the button is selected i can see properties of the button in the properties window on the right hand side i can see for example we have the text property of the button which is currently button one i'm going to change that to press here and notice how it's changed the appearance of the button on the form the other thing i want to change is the name of the button every object that you place on a form will have a name property now it's currently button one because it's the first button which i placed on the form and i could leave it as button one but i want to start using a naming convention btn in lowercase because it's a button and then something meaningful which tells me what the button does for example start you could call the button pretty much anything you like as long as the name doesn't start with a number and as long as there are no spaces or special characters like question marks or exclamation marks in there this naming convention makes it clear what the button does and it also makes it clear that it's a button and that will become important later on when i start writing code there are other properties which i can change as well for example the background color and i have a color palette here which i can use we'll stick with this for now but you'll learn about other properties as and when you need them what i want to do now is write some code that will run when the user of my application clicks on the button to write some code for the button i can double click it the way to think of this is that the code is behind the form my form is still there you can see there's a tab here that's the design view of my form and this is the visual basic view of my form notice that the toolbox no longer has anything on it because it's inappropriate to use it while i'm coding i have line numbers down the left hand side to be honest i don't like these and i'll turn them off in a moment and i can see some code already there and i have to be very careful not to break it for example i can see public class form 1 at the top and end class at the bottom i'm not going to change this these need to be in place in order for the form to work later when you find out more about object oriented programming these two lines will make more sense i can also see the stub of a procedure which will run when the button is clicked private sub button start click notice that's the name that i gave to my button and notice that it's going to handle the click of the button to be more precise it will handle the click event of the button object there's also some stuff going on in brackets here these are called parameters and you'll find out more about parameters later suffice to say leave this exactly as it is for now we're going to write code between sub and end sub so i'm just going to press the enter key a few times and give myself some more room i can also give myself some more room above the procedure and below the procedure sub by the way stands for sub procedure so let's write our first program i'm going to use the message box command notice i'm typing in lowercase and as i type a list of options has appeared visual studio is looking at the letters i'm typing and offering me a command to choose from so i can see msg box here i can ignore it and carry on typing or i can actually select it from the list i'll show you how we can do this more quickly in a moment i'll just press the space bar and i'm going to open a bracket and again there's some more information appearing on the screen it's quite daunting the first time you see this but as you get used to it you'll find it's incredibly useful again i'm just going to ignore it notice how visual studios automatically put the closing bracket on there for me i'm going to open a double quote and again visual studio has automatically put the closing double quote on there and finally i'll type the text of my message hello world all kinds of things have happened here for example notice that msg box has automatically recapitalized that tells me that i typed it correctly i'm getting visual feedback notice also the color coding the literal string which i'm using in my text message is colored differently from the command itself again i'm getting visual feedback on how to use this this is why it's called visual studio let's put another message in now i've just typed the first few letters this time and i'm going to press the tab key on my keyboard to select the rest of it i've saved myself some typing when you get used to it you can write code very very quickly hello world how are you and one more spelling mistake there i'm just going to hold down my control key and tap the left arrow key which will jump me one word at a time through that text and then i can correct my spelling to be honest it doesn't matter what i put inside these double quotes it won't be a problem if on the other hand i mistyped the command i see a red wiggly line underneath it telling me that i've made an error this is what we call a syntax error i'm breaking the rules of the programming language if i move my mouse over it i can see some kind of error message there msg boxes not declared visual studio thinks i'm trying to use something called a variable and i haven't announced that i want to use it more about variables later on let's just get rid of this line altogether okay so there's my program i'll just close up a little bit of the white space i don't need it and i'm going to run the code there's a start button at the top and my form is now on the screen and to test it i'll simply click on the button there's my first message there's my second message and there's my third message and the program has stopped running my procedure may have stopped running but the application itself is still running the form is still on the screen and i can stop this running by pressing the red square up here or i can simply close the form with the red cross here and everything is stopped so there we have it our first program which is just a sequence of messages but it's a program there's one more thing i want to do now and that is to save my work remember a visual studio application can consist of several files so rather than just clicking this little button here which will save the form i'm going to click this button which will save all of the files in my application i can now close down visual studio and return to my application tomorrow in this video i just want to show you how we can customize the integrated development environment the ide that is visual studio so let's start it up again and i'm going to open up the project that i was working on last time notice that it's in the recent files list so i could just click on it here alternatively i can click on open a project or solution let's do it this way for now so we can see which file we need to open up here's my d drive this is where i'm storing my projects and here's the one i was working on last time notice it's a folder inside that folder there's a solution file sln that's the file which ties together all of the other files that make up my application that's the file which i need to open and here's the application i was working on last time here's my form and here's the code behind it a little word of warning first of all sometimes you might accidentally double click on the background of the form itself watch what happens when i do this i've got another procedure stub here called form1 load any code which i write in here will automatically run when i run up the application which will cause the form to load but i don't need this so i'm going to get rid of it i'm simply going to delete this procedure stub another word of warning you might accidentally or even deliberately click on this where it says one reference let's take a look i've clicked on that something has appeared and i'm going to click on this as well i have another tab across the top and what i can see here looks very complicated indeed this is code which runs when you run the form but you don't really need to see it if you're a beginner in fact it's quite daunting when you look at it suffice to say for now it's actually initializing the form it's setting up the form and it's placing the button on there and it's changing various properties of the button i strongly recommend you leave this alone until you have a better understanding of what it does i'm just going to close down this tab and i'm back to something more familiar anyway what i want to talk about now is how we can customize this programming environment you were given some options when you ran it up for the first time but you can change those options inside tools options notice i'm using a color theme blue but you can change it to dark if you wish some people much prefer this to be honest i don't i prefer black on white not white on black it really is a matter of preference i'm going to switch it back to the way it was i can also have finer control over the keyword colors and over the text colors and any other colours that you see on here for that matter we can do this by selecting fonts and colours you can see there's a lot of options here keyword the default color is blue and i can switch that to magenta you do need to be a little bit careful though because some colors have special meanings and it can start looking very messy as well if needs be you can change things back notice there's an option here to use defaults some people like to increase the font size as well it's entirely up to you something else i want to change to give myself some more room on the screen is to switch off these line numbers i can do that by going to text editor all languages and then here line numbers notice i can have different configurations depending on the programming language i'm using and there's one more thing i want to change and that's some of the default file locations i can do that underneath projects and solutions locations you can see i've already set my project's location to my d drive needless to say there are lots more options which you can set in here and i'll be honest i don't know what half of them are but when i need them i'll find them click ok for your changes to take effect in this video about visual basic.net i want to say more about output and i'm going to introduce you to variables i'll start by creating a new project as before it'll be a windows forms application in visual basic give the project a meaningful name and think about where it's going to be saved you can change this if necessary let's start with a button on the form and i'm going to rename the button get in the habit of renaming things that you place on the form as you go along btn that's my convention and then go this is called camel notation because of the capital g it looks like a camel with a hump on its back i'm also going to change the text property of the button and let's write some code that will run when the user clicks on the button to get to the code behind the form i double-click the button let me just remind you you mustn't change or delete this if you do you'll start seeing errors on the screen watch straight away i've got a syntax error up here class statement must end with matching end class i'll just use the undo button to put it back again and i'm going to give myself some white space just give myself a bit more room on the screen here we've already seen that we can display a message on the screen using the message box command like this to test it i simply press the start button that will run the form up and then i can run my code by clicking on the button itself now there are three fundamental constructs when it comes to programming that i'd like to mention now the first of these is sequence the second is selection which you'll see in a later video and the third is iteration which you'll also see in a later video for now let's just say a little bit about sequence sequence simply means that each statement in a program or a block of code will run one after another in sequence so for example i could display each of these words separately run the program press the button and one message after another and i'll stop my application with this red square if i want to display these words in reverse order i can simply change the order of the commands i'm just dragging and dropping and tidy up some of the white space you can have as much or as little white space as you like whatever makes it easy for you to read the program let's give this a try before i continue and talk about variables i just want to show you another command i can use to display a message on the screen messagebox dot show let's take a look this is another message it does exactly the same thing to be honest this is a bit of an old style command which has existed from very early versions of visual basic this is a more modern way of doing things this is an object-oriented approach and it'll make more sense why you might do it this way later when you find out more about object oriented programming for now you can either use msgbox or messagebox.show i'm going to continue with msg box so now let's talk about variables i'll start by placing another button on the form because i want to write a separate procedure switch to the form and drop another button on there notice i'm getting some guidelines as i drag the button around and resize it this helps me to create a nice layout for my form okay let's get in the good habits of naming objects as we go along so i'm going to call this btn variables and i'll change the text property as well to write the code as before double click and you can see i now have a new procedure stub i can start writing my code here let's give myself a little bit more white space below and a little bit less at the top here so what is a variable well a variable is actually a location in the computer's memory where a program can temporarily store data while it's running and while that sounds a little bit complicated they're actually very easy to set up and use let's say for example i want to create a variable to store somebody's first name the first thing i need to do is declare it i need to announce that i want to use a new variable and i do this using the dim statement like this now there are a number of things going on in this command first of all the word dim is short for dimension because i'm actually setting aside a certain amount of memory i'm specifying the size or the dimension of the variable the amount of memory being set aside depends on this which is the data type of the variable when it comes to string variables one byte of memory will be needed for each character in the string but to be honest i don't need to worry too much about that visual basic will look after the memory for me or to be more precise the runtime engine that visual basic depends on will take care of the memory for me the other thing i'm doing is i'm giving my variable a name and again notice that i'm using camel notation and i've prefixed it with st because it's a string variable that's just a convention which i'm going to encourage you to use you might want to know what data type a variable is just by glancing at its name so that's my variable declaration i've got a green wavy line underneath it to tell me that i haven't done anything with it yet unused local variable so let's now assign a value to it notice i'm typing in lowercase i'm being offered the name of the variable in a list so i'll just press the tab key to select it and i'll say st first name is equal to my first name notice that the green wavy line has disappeared now because i'm using the variable in earlier versions of visual basic you would have to use the let command in front of this you'd say let st first name equal kevin let it become kevin in this version of visual basic we don't use let at all but what you need to appreciate here is i'm putting the string kevin into that piece of memory which i set aside because the string is one two three four five characters long it's going to take up five bytes of memory as i said before though you don't really need to worry too much about that okay now i'm going to output the contents of that variable and i'll do that using messagebox notice that i haven't put double quotes around the name of the variable because i want to output its contents i don't literally want to output the string st first name let's see what happens i'm outputting the contents of the variable i want to make the message a little bit more friendly so i'm going to join the contents of the variable with some literal text like this you can see that this is a literal string because it's inside double quotes and this is the contents of my variable and i'm using the concatenation operator which is an ampersand to join the two together we call this string concatenation i can concatenate something onto the end of it as well again another concatenation operator let's see the effect hello and welcome kevin i hope you are well i want you to notice that i put spaces inside these text strings notice there's a space after the letter e let's just remove it for a second and see what happens i've also got a space there inside the string immediately before the eye i'll just take that out as well look what happens you can see the message is a little bit messy let's tidy it up okay i'm going to declare another variable to hold my last name so another dim statement and i'll assign a value to this variable as well and i'll include the last name as part of the message a common mistake is to not use enough ampersands watch what happens if i get rid of this one you can see i have a syntax error the message isn't particularly helpful but i know that there's something wrong with the way i've concatenated this string together so let's put the concatenation operator back in place another common mistake is not to use enough double quotes so again i'll take out one of those double quotes and you can see that the whole thing seems to be a problem one little error and i've got red wavy lines all over the place this is not particularly helpful just remember double quotes and brackets come in pairs if you have an opening double quote there has to be a matching closing double quote if you have an opening bracket there has to be a matching closing bracket let's try this now you can see kevin drum has come out as one word there's no space in between the two i can fix this easily i need to concatenate a space in between those two variables a space is just another character let's take a look much better notice that i've put my dim statements my variable declarations at the top of the procedure i didn't have to do this as long as i declare a variable before i try to assign a value to it i can put my dim statement wherever i like so for example i could declare the last name here and then assign a value to it that's absolutely fine what i mustn't do is try to assign a value to it before i declare it you can see i have a syntax error local variable st last name cannot be used before it has been declared the sequence of operations is important although what you can see here is perfectly okay i like to put all of my declarations at the top of the procedure keep them all together it actually makes the code easier to manage particularly when you have a lot of code i told you that a variable was a temporary storage location which your program can use while it's running when this program has done its job and it comes to an end the memory being used by the variables will be released it'll be freed up for something else to use but i can change the contents of a variable while the program is running that's why it's called a variable its contents can vary so for example i can do this i'm just going to copy these two lines of code paste them underneath they're still part of the procedure and i'm assigning new values to those variables which i'll output in the same way as i did before i can just borrow this line of code and copy it so watch what happens when i run the program hello and welcome kevin drumm i hope you are well hello and welcome mervyn drake i hope you are well this makes the point that the contents of a variable can change while the program is running i can assign different values to those variables at run time in the next video i'll say more about the different data types that you can use when you declare a variable and what implications this has for your code in this video i want to say more about different variable data types i'm going to store some details about a car let's start with a new button on the form give it a name and change the text property double-clicking will allow me to write the code okay so i'm going to start with a couple of string variables to store the make and the model we've come across string variables already let's assign some values a ford escort a classic car i also want to store the number of doors that this car has this time i'm using a data type of integer an integer is just another name for a whole number notice the naming convention i'm using i doors i for integer i want to store the color of the car this is going to be another string variable i want to store some information about whether or not this car has been taxed this time i'm using a data type of boolean named after the computer scientist george boole a boolean variable can have one of two values true or false this car has been taxed boolean variables are good when you have yes no type data for example whether somebody is a vegetarian or not whether something is switched on or something is switched off i also want to store the engine size another integer 1200cc i'd like to store the price of this car i'm using a data type of decimal decimal is the most suitable data type when you want to store money values i could have used double and i could have used single because all three data types decimal double single allow me to have a decimal point with decimal places after it but double is twice as accurate as single i can have more decimal places and the data type decimal is the most accurate of them all which makes sense when you're doing calculations with money the final thing i want to store is the date that the car was registered so i'm going to use a data type of date there's a special way that i have to assign a value to a data variable notice i'm using the hash symbols to enclose the date i should also point out that this is not the 11th of february but the 2nd of november when you type a date you need to type it in american format which is the month followed by the day followed by the year when i display this on the screen for example in a message box it'll be displayed according to the settings in my computer's control panel you'll see in a moment that my computer is set up to display dates in british format now let's build a message box command to display all of this data notice the concatenation operators between the variable names and notice also that i'm concatenating spaces between these data items now you can see i have a bit of a problem here with reading the code i've written on the screen nevertheless let's test it and see if it runs there's my message and it looks okay notice that the day and the month of the date are the other way around from the way i coded it i've written the date in american format but it's being displayed in british format what i'd really like to be able to do is display each data item on a separate line within the same message box let's see how to do that instead of concatenating spaces in between each data item i'm going to type a special constant i'll say more about constants later suffice to say i'm just going to type vbnewline and i'll replace each space with this let's just copy and paste it ctrl c to copy ctrl v to paste i still need the same number of concatenation operators to join all these different bits and pieces together let's see how it looks now well that is certainly a nicer message but now i want to do something about the problem that i can't actually read the whole line of code i could give myself some more space on the screen by just dragging this bar across a little bit but even then i can't read the whole line of code i essentially want to wrap this text on the screen well i can do this after the ampersand here in fact i can put this pretty much anywhere i'm just going to leave a space and then type an underscore character when i press enter i've moved the rest of the line onto the next line down i can do that again here notice the underscore characters have actually disappeared but this is still just one line of code it won't change the appearance of the message box but it just allows me to read the code more easily on the screen let's make sure it still works yeah that's absolutely fine in the next video i'll show you how we can capture input from the user of an application so we can assign the contents of these variables at runtime rather than hard coding the data like we've done here i want to show you how to capture input from the user of your application and i'll be doing it by means of this form and you'll also see how to use some of these extra controls that we can place onto a form before i do let me just show you a quick and easy way we can capture input from the user by means of the input box function i'll drop a button on the form first give it a name and a text property double-click to write the code the input box function will capture one piece of data specifically it'll capture a string i'll need a variable to put that piece of data into so let's declare a string variable first of all and then i can assign a value to it by means of the input box function just like this and to prove it works i'll output the contents of that variable i'm concatenating the word hello in front of it let's give it a try press the button to launch the procedure and there's the input box prompt please enter your first name that's working fine so it's a quick and easy way to prompt the user for some input but what i really want to talk about in this video is how we can use controls on the form to capture input so i'm going to delete the code you can see here and do something else instead let's go back to the form i'm going to place a text box on the form here it is in the control toolbox i'll give the text box a name notice at the moment it's called text box one i've prefixed the new name with txt to indicate that it's a text box and then i'm calling it first name because that's the data i want to capture i'm trying to keep the name meaningful notice the camel notation as well you'll see the benefit of doing it this way in a few moments i'm also going to put a label on the form so that the user of the form knows what to type into the text box here's the label control and again i'm going to change its name to keep it meaningful lbl for a label and then something to indicate its purpose a label also has a text property which i'm going to change and you can see that is what appears on the form while i'm at it i'm going to add another text box to capture the user's last name and a matching label and one more text box to capture the user's gender notice that a text box also has a text property but anything i type in here will actually appear in the text box it will become the default data if a user doesn't type something into the text box i'm going to leave it blank and we'll have another matching label to go with this text box there are a couple of things you need to be aware of when you're placing controls on the form each control must have a unique name so this one you can see i called it txt first name there's the name property and this one i called txt last name let me just make the mistake of giving this text box the same name as the other one and see what happens property value is not valid take a look at the details and it's telling me that the name is already in use by another component something else on the form has already been called txt first name if this happens just cancel and find out which one is the offending control something else i should mention is you can't have spaces in a control name so let's put a space in this text box name again an error message and maybe i'll even try putting a question mark on the end of the name another error message so there are some limitations as to what you can call a text box or indeed any other control on the form the text property on the other hand of a label or a button can be pretty much anything you like okay let's just tidy up the layout a little bit i'm watching the guidelines for assistance and you can also use the format menu to help you control the layout of a form see i have options for alignment horizontal and vertical spacing this one is particularly handy if i select all of these text boxes i can say i want to make them all the same width for example and i can make them all the same height if i want to move things around as a group i just draw a box around them to highlight them and i can drag them to a new position you can play around with the various tools available to improve the cosmetic appearance of your form when you have time but for now i just want to show you how we can capture some data so let's write the code for the button i'm going to start by declaring three variables into which i'm going to load the data that i capture i'm using a standard naming convention again st because these are string variables and then of course something meaningful in camel notation i've just spotted a spelling mistake as well let's fix this now i'm going to take the information that the user types onto the form and load it into these variables starting with the first name st first name equals a single equal sign means i'm about to assign something to this variable and the information i want is on the form in a text box called txt first name i've just typed the first three characters of the text box name txt and i'm being presented with a list of the text boxes on the form you can see why i use this naming convention as long as i make sure that all of my text boxes begin with txt i'll get a nice little list of them so i'll select txt first name and i want to take the text property in other words the text that the user typed into that text box and i'm going to load that into my variable so this reads as take the text from the text box called txt first name and assign it to that variable let's do the same with the other variables and finally i'm going to output the data in a message box just to make sure it worked i've included a space between the first name and the last name and i've concatenated some extra text in my message as well let's see what happens when we run it then type in some information and there's the output from my procedure if i dismiss the message box the application is still running so i can change the data here the program is assigning new values to those variables overwriting the existing ones one more time so there you have it capturing data from a user by means of text boxes on a form let's quickly take a look at another control which i can use on the form i want to show you a list box and i'm going to use this to capture the user's occupation so let's give it a name lst occupation lst because it's a list box i'll put a label on the form to go with it so that the user knows what the list box is for and i'm going to include some occupations in the list box that the user can choose from first of all make sure that the list box is actually selected and then use the items property there's a little button here which will allow me to add a collection of items click ok and i now have a populated list box let's capture the user's selection i need a variable to store it in and i can capture the user's selection in a slightly different way i'm using the selected item property let's try it out hello kevin drumm you are a male teacher i can also add items to the list box programmatically in other words in my code i'll quickly show you this and then you can experiment with it yourself you might remember in an earlier video i showed you how you could write code when the form loads i'm going into the form design environment and i'll double click the form itself i now have a procedure called form1 load any code i write here will run immediately after i start the application but before the form appears on the screen and i'm going to add some extra code to put a few more items into my list box i am adding something to the collection of items which are inside that list box i'm just going to make sure that the list box is big enough to display everything and let's give it a try hello beatrix potter you are a female writer before we look at some more code i want to introduce you to some of the facilities that come with visual studio for debugging your code in other words tracking down errors in the code the first and probably most useful one that i want to talk about is being able to set a breakpoint and then step through the code i can set a breakpoint by clicking on the grey bar here that's a break point now i'm going to run the program watch what happens i'm now in what's called break mode or debugging mode my application ran at full speed until it came to the break point and now it's suspended and i can step through the code one line at a time there are a number of buttons i can use to do this up here step into step over step out i'll say more about these two later the most useful one is step into notice i can also use the function key f8 to do the same thing so when i click the button i'm getting a message about how the stepping facility will behave i'm not too worried about this for now i'm just going to say i don't want to see these messages again it's highlighting the line of code that it's about to execute next and now it's about to execute this line of code and again it's about to execute this line of code when i'm in debug mode i can hover over the name of a variable to see its contents so i can see that the string male has been assigned to this variable drum has gone into this one and kevin has gone into that one if i take a look at this variable it hasn't been assigned a value yet because this line hasn't executed yet let's continue stepping and i can see there's something inside that variable now final line of code in this procedure will do some output so i've been switched back to the user interface and finally the procedure will come to an end my application is still running the form is still on the screen but the procedure which i launched when i clicked on the button has now finished i can use as few or as many break points as i like i'm going to remove this break point just by clicking on it again and i'll place a break point here instead i'm also going to place a break point on the forms load event handler let's run it again now as i told you in the previous video when you launch a windows forms application the form is loaded into memory before it hits the screen so the forms load event handler is running first i'll step through that and it's populating the list box when that's complete the form can hit the screen and clicking the button causes the button's click event handler to start running and we've seen this before when we're in debug mode there's some extra windows that you might want to switch on a particularly useful one is called the locals window you can find it here on the debug menu debug windows locals what it's showing me is the contents of any local variables in other words variables which have been declared within this procedure i'll say more about the difference between local and global variables later on suffice to say for now this is an alternative way of finding out what's inside a variable i can see a nice summary down here there's additional information in this window as well which pertains to these parameters which i mentioned in another video we'll say more about these later with the locals window i can actually change the contents of a variable on the fly as it were i just double click it here and retype it i've overwritten the existing value of that variable if you've finished stepping through your program you can stop the execution just by clicking on this red square or you can press continue and it will jump you straight to the next breakpoint if there is one at this point i just want to return to a type of error that you've seen already and that's the so-called syntax error for example if i misspell the word text i type text on the end i've got a red wavy line if i open a bracket but forget to close it again that's a syntax error i can see a red wavy line on the end of this keep an eye out for these because your program won't run properly if you don't fix them i like to fix them as i go along but let's see what happens when i try to run a program which has got syntax errors like this in it there were build errors would you like to continue and run the last successful build well that begs the question what does it mean by build so let's say no and i'm going to switch on something called the output window watch what happens when i try to run the program again build xero succeeded one failed this tells us something very important about vb.net programs when you write a program you're writing source code code that a human being can understand but before you can run a program it has to be compiled what that means is it has to be turned into machine code binary ones and zeros that the computer can understand when you press the start button visual studio will automatically try to compile the program first another name for compiling a program or compilation is to build the program so you can see here the program has failed to compile the build failed and i'm very kindly being asked would i like to use the last successful build would i like to run the version of the program that compiled successfully previously well in this case the answer is no i want to fix this version of the program so i'm going to click on no and now i have a list of errors this is really just a summary of the same information that i saw with the red wavy lines i'm being told that it's expecting a closing bracket a double click on there and it jumps me to where i need to do the fix and i'm being told that text is not a member of text box in other words text is not a property of a text box a double click and it will jump me straight to that line i can fix it here now as i said before though i like to watch out for the red wavy lines while i'm coding and fix them as i go along i'll show you some more debugging facilities as and when i need them in later videos in this video i'm going to talk about how we can work with numeric input from the user in other words how we can do calculations with number data before i do i'm going to build myself a simple little interface with a couple of text boxes and a button notice how i've been naming the controls as i go along this will make the code easier to understand the first thing i'd like to do is add together two numbers that the user types onto the form so i'll start by declaring a couple of variables remember the data type integer means a whole number i'm going to declare another variable to store the result of the calculation and now i'm going to capture the data that the user types into those text boxes adding these together couldn't be simpler i result equals i number one plus i number two let's output the result and see if it works 12 plus 5 is 17. let's try something else let's subtract one number from the other i result equals i number one minus i number two i'll just borrow that message box statement and we'll run the program again so that's the two numbers added together and that's what we get when we subtract 5 from 12. what about multiplication to multiply two numbers together we use an asterisk that's the multiplication symbol when you're programming twelve plus five is seventeen twelve minus five is seven and twelve times five is sixty bit of copying and pasting to speed things up to divide one number by another use a forward slash so this reads as i number one divided by i number two twelve plus five is seventeen twelve minus five is seven twelve times five is sixty and twelve divided by five is two well not quite but remember we're working with integers here we're working with whole numbers when i divide one integer by another and store the result in an integer variable vb is automatically going to round to the result either up or down let's improve on this instead of using integer variables i'm going to use a real number type let's use a double i'm also going to change the naming i've used here dbl for a double strictly speaking it doesn't matter what i call these variables but i want the names to be meaningful and i want the names to reflect the data type let's see what we get this time same as before 12 plus 5 is 17 12 minus 5 is 7. 12 times 5 is 60 but 12 divided by 5 is 2.4 that makes more sense just to be clear about the way a variable works i'm multiplying two numbers together here and i'm storing the result in this variable called dbl result when i perform a second calculation i'm storing the result in the same variable what's happening is i'm overwriting the existing value in dbl result i lose the value which was generated by the first calculation when i do the third calculation i overwrite the value inside dbl result again so i lose the result of the second calculation by the time my program comes to an end this contains the result of the first number divided by the second number if i wanted to keep the result of each of these calculations then i should have declared four separate variables these are called arithmetic operators these are the basic operations that we might want to perform with numbers there are a couple more let me show you them that's the carry symbol which is normally above the number six on your keyboard and what it means is raised to the power of so it's going to raise number one to the power of number two twelve plus five twelve minus five twelve times five twelve divided by five and twelve to the power of five that's twelve times twelve times twelve times twelve times twelve another useful operator is integer division i'm going to use a backslash instead of a forward slash in some programming languages you would use the word div in fact the pseudo code that you see on most exam papers will use the word div in visual basic we use a backslash let's take a look that's the effect of using a backslash instead of a forward slash 12 is being divided by five but only the whole number part of the result is being kept twelve divided by five is two with two remainder we're ignoring the remainder let's try fifteen and four fifteen plus four is nineteen fifteen minus four is eleven fifteen times four is sixty fifteen divided by four is three point seven five that's fifteen raised to the power of four and that's 15 divided by 4 ignoring the remainder 4 goes into 15 three times the last arithmetic operator that i'd like to show you now is mod number one mod number two mod is the remainder after whole number division let's see what this does let's go with 24 and 9 this time i'll just move the form across so you can see the code as well 24 plus 9 is three twenty four minus nine is fifteen twenty four multiplied by nine is two hundred and sixteen twenty four divided by 9 is 2.6 recurring the number of decimal places you can see there is governed by the data type 24 raised to the power of 9 is this rather large number 24 divided by 9 using integer division is 2 9 goes into 24 twice and 9 goes into 24 twice with 6 remaining that's what mod is giving me it's the remainder after whole number division let me finish with a word of warning i'm going to run this program again but i'm not going to enter any data i'm going to leave these two text boxes empty straight away i have an error message conversion from string to type double is not valid this tells me something about what's going on behind the scenes let's stop the program and put a break point on this line when you type something into a text box it's actually a string notice here text equals 5 7 in double quotes when this line of code executes vb will automatically convert the string five seven into a number you can see dbl number one has got a zero in it at the moment that's the initial value of any numeric variable until you assign something else to it step through the code the text box contained five seven but the variable contains fifty seven behind the scenes visual basic is automatically converting the string into a double because it can but notice that my second text box contains a zero length string a pair of double quotes with nothing in between them it's a string but it just doesn't have any length and when this line of code executes vb will attempt to convert that zero length string into a number but of course it can't and my program has crashed this is what we call a run time error the program crashed while it was running it crashed at run time another name for a runtime error is an exception so you can see here i have an unhandled exception i'll talk more about runtime error handling or exception handling in a later video but for now with this program we just have to expect the user to do the right thing not to leave any of the text boxes blank in this video i'll say something about complex arithmetic that is arithmetic expressions that contain more than one arithmetic operator let's write some code let's imagine we're building an application for a cake shop and the application will calculate the total cost of a number of cakes i'm not going to capture any input i'm just going to hard code the data to keep things simple so i've declared three variables one for the price of a cake one for the quantity of cakes and one to store the total cost of however many cakes being bought let's initialize these variables with some data as i said i'm hard coding the data so i can focus on the calculations but of course i would probably want to capture this data from text boxes on the form so to calculate the total cost of ten cakes at a price of five pounds per cake these are good cakes by the way i'll use the multiplication operator and let's output the result fifty pounds worth of cakes no surprises there now suppose for a moment we want to calculate a discount of let's say two pounds per cake you might be tempted to try this take the original price subtract the discount and multiply it by the quantity five pounds per cake minus two pounds per cake that's three pounds per cake multiplied by ten i might expect a result of thirty pounds let's take a look minus 15 pounds not only are we giving the cakes away we're giving money to the customers as well that's totally unsatisfactory what's going on well there's an order of operations that applies when it comes to complex arithmetic expressions by a complex arithmetic expression i simply mean an expression with more than one operator this expression includes a minus sign and the multiply sign the order of priority is that multiplication is done first so in this case the discount is being multiplied by the quantity which is twenty and then that is being subtracted from the price five minus twenty is indeed minus fifteen if i want the discount to be applied first in other words i want the subtraction to happen first i can control it using brackets or parentheses as they're otherwise known like this so now anything inside the brackets will happen first and there's the 30 pounds i was expecting you may well have come across this already you might have heard of bodmas bodmas stands for brackets order division multiplication addition and subtraction that's the order of priority of the arithmetic operators order by the way means exponentiation raising something to the power of something else so what we're saying is anything inside brackets will be done first if there's an exponentiation operator in the expression that will happen next followed by division multiplication addition and subtraction the truth is division and multiplication have the same priority also addition and subtraction have the same priority so perhaps we should say to indicate the fact by the way i typed a single apostrophe before i wrote this this is not code this is simply a comment which i've added to my code comments aren't executed they're not part of the program a comment is just something that i can put in my code to help me to understand it now let's suppose for a moment i want to add a charge for postage and packaging to the total cost of this order we'll have a flat charge of three pounds and i'm just going to add it to the end of this calculation thinking about the order of operations whatever's in brackets will happen first then that will be multiplied by the quantity and then finally the postage will be added on so i don't actually need to include any brackets here 33 pounds as expected but there's nothing to stop you from adding brackets if it helps you to understand the code so for example i might do this i'm saying do all of this first and then have the postage at the end something else you may have come across is this pemdas this stands for it's essentially the same thing as bodmas you might have noticed that the m and the d are the other way around but that just makes the point that the order of operations when it comes to division and multiplication is irrelevant now beware you might come across this that's the cost of my cakes that's 10 minus five plus two of course ten minus five is five plus two is seven that is ten plus two minus five ten plus two is twelve minus five is also seven all i've actually done is swap around the order of the operations but ten minus two plus five is thirteen let's be clear i haven't just swapped around the order of the operations i'm changing the number which i'm subtracting from 10 10 minus 2 is 8 plus 5 is 13. it's a different calculation the same applies here in the first two examples all i've done is change the order of operations i've got 10 divided by 5 times 2 or 2 times ten divided by five but in the third example it's a different calculation it's five divided by two multiplied by ten so beware bodmas and pemdas both apply they do tell us the order of operations when it comes to complex calculations but complex calculations can also be quite deceptive there are three fundamental constructs in most high-level procedural programming languages such as vb.net and they are sequence selection and iteration in this video i'm going to introduce selection that means executing one block of code or another depending on the outcome of a test one way we can do this is using the if statement let's start with a simple user interface i've said it before and i'll say it again get in the habit of naming your form controls as you place them on the form i'm going to ask the user what country they come from and then give them an appropriate greeting i'll capture the input from the form by assigning it to a variable and now i'm going to use an if statement to test the contents of that variable if the country is equal to australia then i'm going to output the message g'day mate i want you to notice that i'm using the equal sign to check if two things are equal whereas here i'm using the equal sign to assign something to a variable in some programming languages you'll use a slightly different approach for example in python if you were checking for equality you would use two equal signs in vb a single equal sign can be used either for checking or for assignment so let's try it out if i input australia i get the australian greeting if i input something else nothing at all that doesn't mean my code isn't working it's doing exactly what it's supposed to do this is what we call a one line if statement i can execute one command depending on the outcome of the test but if i want to execute multiple commands depending on the outcome of a test i'm going to use a block if statement i've moved that command to the next line down visual studio has automatically added an end if and now between the if and the end if i can have as many commands as i like so watch what happens now g'day mate good on ya no worries if i don't type australia if i type something else nothing happens at all now a word of warning if i put something after the word then that's a syntax error end if must be preceded by a matching if this line of code is complete it's syntactically correct however you can't have an end if on its own if you're going to use a block if there should be nothing after the word then if there's nothing after the word then and i forget to use end if again i've got a syntax error if must end with a matching end if so you have a choice you can either use a block if or a one line if but whichever one you use you have to use it correctly when it comes to a block if i can have multiple else if clauses as part of it like this else if country equals france bonjour commented let's try it out those are my three australian greetings and if the country is france bonjour commented however if i enter something which isn't france and isn't australia nothing let's include another elsif else if country equals japan konichiwa chelsea i think i pronounced that correctly let's try it out now and there are my japanese messages i can have as many else if clauses as i like in a block if statement and i can finish with a single else clause if i don't type australia france or japan then it will say hello there i hope you are well so everybody gets something now just a small word of warning the tests that you perform with an if statement are case sensitive watch what happens if i type australia in lower case the block of code in the else clause is executing because i didn't use a capital a i can remove the case sensitivity of this test by converting the contents of the variable st country into uppercase like this i'm saying take the content of st country convert it to uppercase and then put the uppercase version of it back into the variable overwriting the original contents of that variable and now i'm going to check to see if that is equal to this it doesn't matter what type of case i use when i'm typing in the country i've removed the case sensitivity from the test let's just step through this to be sure what's going on i'll put a break point on the procedure so i've typed in lowercase australia that's what i've captured into this variable and then i've converted it to uppercase australia so i'm asking if uppercase australia is equal to uppercase australia and notice how execution has passed to the end of the if block because the australian greetings have been displayed there's no need to perform these other tests one final thing to say i've converted the user's input into uppercase and i might not want to leave it in uppercase notice this once the if block has completed any code which comes after it then executes for example this message box statement but notice that st country now contains uppercase japan i might want to leave it the way it was when it was input by the user so rather than doing this which replaces the existing contents of the variable i'm going to do this the content of the variable is only being converted to uppercase for the purpose of the test but i'm not reassigning the uppercase text back into the variable i'm converting the text to uppercase on the fly as it were watch what happens now by the time we get to the end of the program the contents of the variable are still in their original state you might like to try writing a similar program yourself have a single if block with lots of else if clauses to greet people from different countries in the previous video of this series i showed you how to use an if block to execute a block of code conditionally in other words to decide whether or not to execute a block of code the if block allows you to use one of the three constructs of high-level programming languages namely selection in this video i want to say more about the if block and the kind of tests that we can perform with an if block i've already created a new windows forms application and i've put three controls on the form i have a label a text box and a button notice that i've named the text box txt exam score and i've named the button btn get grade the idea is that the user of this application will type in an exam score and then the program will calculate the grade let's write the code and see how we can use logical operators to build complex conditions i'll start by capturing the score into a variable i'm assigning the contents of the text box to an integer variable called i score now the first thing i want to do is check whether it's a valid score let's suppose that you can only score between 0 and 100 on this test there's a few things to notice here i'm asking if the score is less than zero this is the less than symbol and let me be clear less than zero means minus one minus two minus three zero is not actually less than zero zero is equal to zero i'm also checking to see if the score is bigger than one hundred given that you can't score more than one hundred on this particular exam anything bigger than one hundred would be invalid if the score is less than zero or the score is greater than 100 then we'll display a message saying this is not a valid score i'm also giving the user of my application some guidance i'm not just telling them what they did was wrong i'm telling them what they should do instead which is good practice for an error message then notice i'm exiting the program i've put another line of code here just to prove the point when we drop out of the if block normally this line of code would be executed but because i've said exit sub this will force the program to stop there and then let's give it a try if i type a score of let's say -1 this is not a valid score i'm getting the error message let's try a score of 101. again not a valid score let's try a score of 99 and i want you to notice that we've dropped out of the if block and we're getting that message at the end of the program saying all done it hasn't actually done anything yet we'll deal with that in a moment just to be sure i should really test the value zero zero is valid zero is a perfectly good value and i should also test the value 100 and that's fine as well so that's the beginning of my exam checker program and i'm using something called a logical operator the word or is one of three logical operators which you'll come across the less than symbol and the greater than symbol are called relational operators that is the condition clause of my if statement and because it's effectively performing more than one test we call it a complex condition now before i try and work out what the grade for a particular score is i'm going to keep it really simple and just test to see whether somebody has passed or failed so if the score is bigger than or equal to 50 it's a pass if the score is less than 50 it's a fail notice the greater than or equal to symbol that's another relational operator let's give it a whirl a score of 45 is a fail and notice all done is being displayed unconditionally that's going to happen one way or the other a score of 55 is a pass now it's good practice when you're testing a program like this to try all of the boundary values and by boundary values i mean 50 is a boundary 100 is a boundary zero is a boundary so let's try a score of 50. 50 is a pass it's also a good idea to test parts of the program that we've already tested because when you add new code you might introduce bugs so i'm going to test less than zero again minus five is not valid and neither is 105 it seems to be working now you might have already noticed that i've used three separate if blocks in the previous video i showed you one if block with multiple else if clauses and i'd like to point out the difference between the two i'm going to set a breakpoint on this program and run it up again and we'll put in a failing score let's say 30 and now i'll step through the code so we assign the contents of the text box to the variable we check to see if the contents of the variable are within range in this case they are so we jump to the end of this if block then we check to see if the score is greater than or equal to 50 which it isn't so we jump to the end of this if block and then finally we check to see if the score is less than 50 which it is and we report that it's a fail all done let's do that again but this time i'm going to put in a passing score let's say 75 assign the content of the text box to the variable check that it's in range which of course it is so we jump to the end of the first if block check to see if the score is bigger than or equal to 50 which it is report that it's a pass and now we're checking to see if the score is less than 50 which of course is unnecessary we're doing a test that we don't need to do we've already established that it's a pass to make my program more efficient i'm going to use a single if block with multiple else ifs my validation test where i checked to see that the score was actually within range i could have left as a completely separate if block but don't forget there was an exit sub in there and it may well be that there's some code i want to execute unconditionally at the bottom of the program if you use exit sub early on that won't happen so i've included this as well inside the if block with multiple lcif's let's give it a go a score of 67 is a pass all done let's step through it and watch what's happening the score is in range the score is bigger than or equal to 50 so we report a pass and then we drop out of the if block we don't need to do any more tests so although it's perfectly reasonable to have multiple if blocks each performing a separate test it may be better to use a single if block with multiple else ifs and then the program doesn't have to work as hard now admittedly with a little program like this i'm not going to notice a lot of difference but as you start writing longer more complex programs then small adjustments will add up and your program will run faster okay it's one thing writing a program that works efficiently but it also has to be robust we want a program that you can't crash and i can crash this one easily watch i'm typing text into the text box rather than a number invalid cast exception conversion from string 10 to type integer is not valid this makes the point that when you type something into a text box it's a string there's the word ten with double quotes around it and i'm trying to put that string into a variable that's designed to hold integers whole numbers i'll run the program again with a breakpoint but this time i'll be a well-behaved user notice that the text box contains the string 1-0 the text box does not contain a number it's a string of characters but because i'm trying to assign it to an integer variable vb will attempt to convert it into an integer and the string 1 0 can be converted into the number 10 so everything is fine the program does not crash the text 1 0 in double quotes has been converted into the number 10. converting data from one type to another is called casting and vb was able to do the cast let's run it again with something it can't handle vb will attempt to convert the string five into a number and of course that is an invalid cast it can't do it the last thing i want to do is give my program to a user who can inadvertently crash it so let's add some extra code to get around this problem before i attempt to initialize the variable i score with the contents of the text box i'm going to test to see whether or not vb will be able to convert it into a number like this is numeric is a special built-in function which will allow me to test whether or not something can be converted into a number in this case i'm testing the contents of the text box let me be clear it doesn't convert it into a number it simply asks the question can it be converted into a number when i perform this test the outcome will either be true if it can be converted or false if it can't so i'm saying if is numeric equals true if it can be converted into a number then i will do this line of code i'm initializing the variable conditionally if it can't be converted then i give an appropriate error message and i am exiting the program this time because there isn't much i can do with that data unless it is actually a number so there's my little validation routine let's give it a go in some text you must enter a number and i'm not getting the all done message because i've forced an exit from the program now there's one more thing i can do just to improve the efficiency of the program a little bit and that's to tell vp that i want to convert the contents of the text box into an integer rather than allowing vb to make the decision for me and i can do it like this c int is short for convert to integer and of course my program is only going to do this if it can i've already made sure of that with my is numeric test if i left this out it would still work but i'm leaving it up to vb to decide what to convert the contents of the text box into an integer a double a single and it will make that decision based on the variables data type i'm just taking the decision out of vb's hands and it will result in a very slight improvement in performance i'll talk more about special inbuilt functions in another video but you've seen two already is numeric and c int in the previous video i showed you how to write this little routine to check if an exam score was a passing score or a failing score i made use of one of three logical operators i used the or operator in this video i want to say a little bit about the other two logical operators namely and and not i'll be adding more else if clauses to my if block to come up with a grade for a particular score rather than just pass or fail in the previous video i also paid particular attention to validating the user's input you can see my program has an if block right at the start to check if the user's input can be converted into a number and if it can then it does it converts it into an integer i've explicitly performed the type conversion also known as a cast using the c inter function if i hadn't used c int then v b would have done the cast for me if it could if v b does it it's known as implicit type conversion explicit type conversion is more efficient before we add some more logic to this program i just want to point out that it's not perfectly robust yet i can still crash this let me show you how you've seen that if i type text i've essentially trapped the error but what if i put in a number which is too big that is an extremely large number and it's crashed my program an integer variable occupies four bytes of memory that is 32 bits so the maximum number of values that you can store in an integer variable is 2 to the power 32 it works out to about 4 billion now since we also need to store negative integers that means we can go from about minus 2 billion to positive 2 billion the number i entered was bigger than 2 billion and i've got what's known as an overflow exception there's a possibility that the person who's using my program might type in a very large number and trigger this runtime error this is a fairly easy one to sort out i'm just going to change the user interface notice that my text box has a max length property that's the maximum number of characters i can type into the text box you can see it's over 32 000. i can type 32 767 characters into this text box well my exam score is never going to be bigger than let's say a hundred so if i limit the number of characters that you can type into the text box to let's say three then the maximum value you can put in there is 999 a simple fix i can't enter a number bigger than three characters long now let's add some more logic to the if block depending on the score i want to award a grade which is either a b c d e or f i'm going to keep the test which checks to see if the data is within range but i'll add some more else if clauses if you score less than or equal to 20 that is a grade f if you score more than 20 and less than or equal to 30 that is a grade e notice the use of the logical operator and what i'm saying is the score must be bigger than 20 and it must also be less than or equal to 30. a score between 31 and 40 will get you a d and anything between 41 and 50 we'll call that a c in this particular examination anything between 51 and 70 will get you a b notice i've got a syntax error there's a red wavy line what's it telling me expression expected not particularly helpful but this is actually quite a common mistake when you're writing complex expressions which include logical and relational operators i need to include i score again right here if i'm using a relational operator to compare two things such as a variable and a number then i have to say what two things i am comparing i have to be explicit okay so every other school is going to get you a grade a so i can just use an else clause now and that is all of the possibilities taken care of now notice i've been very very careful not to overlap the ranges of scores this range is between 21 and 30 inclusive this range is between 31 and 40 inclusive there's no overlap if for example i made this mistake and i said greater than or equal to 30 then a score of 30 falls into this range and it falls into this range then my program might not work i might get some peculiar results so just be very careful about that if you think about what's going on here a score of 30 is not covered either by this test or by this test think it through and you'll see that a score of 30 will actually get you a grade a but that should be fine there's one more logical operator which i haven't mentioned and to be honest i don't really need it in this scenario but i can make use of it just to illustrate how it works instead of asking if the score is out of range i'm going to just turn the logic of that question around and ask if the score is not in range in a sense it's the same question if the score is not in between one and a hundred then it must be out of range now all that remains is to test the program thoroughly there are several possible execution paths and i should really test them all i should also make a point of testing things which i've tested before for example my validation routine here i need to make sure that i haven't introduced any bugs when i added new functionality this is called regression testing i should also check all of the boundary values i should try a value of 0 a value of 100 a value of 20 30 40 70 and i should also try valid values within the ranges which i've specified in my if statement namely 25 35 45 60 75. if you don't test thoroughly and then you start adding more code to this then you're building on shifting sand do it carefully now and you'll save yourself a lot more work later on and straight away i found a problem it is possible to score zero on an exam that should have been greater than or equal to zero that's better as i said make sure that you test every possible pathway through the program i'm going to show you an alternative to the if block another way to perform selection in your code i've created a new project let's pop a text box on there to capture some input and a button to run my program the idea is that the user types in the temperature maybe 15 degrees and then the check temperature button will tell the user whether it's cold freezing warm hot that kind of thing and although i could allow vb to do the implicit type conversion for me i'm going to do it explicitly remember a text box captures text input i'm converting it into an integer i'm not going to worry about my program crashing if the user doesn't behave themselves and type in a number now this is what the select case construct looks like it begins with the word select case and then the name of the variable which i want to test in this case i temperature and it finishes with end select and now i'm going to say in case i temperature is equal to zero i will output the message freezing if the temperature is less than zero i'm going to output an appropriate message for that as well if the temperature is between 1 and 10 that's cold notice the syntax case 1 2 10 that means everything between 1 and 10 inclusive so 1 and 10 are included as well if it's between 11 and 20 it's warm and let's say everything else is hot and there it is the select case construct now i could have done exactly the same thing using an if block but arguably this is a little easier to read it's somewhat easier to see what's going on by the way i could execute multiple lines of code as a result of each test okay it's a bit silly but you get the point i'm selecting one block of code or another depending on the outcome of a test let's give it a try minus five is sub zero zero is freezing water will freeze and you can go skating hate is cold 15 is warm and 200 is hot you should really test all of the boundaries as well so you should see what happens if you enter a 1 or a 10 or 11 20 and then something incredibly big this program can be crashed as well because we could type in some text but of course we could add some additional logic to validate the data before the code gets into the select case block by the way there are some other things i can use in a case statement for example i could say case 1 comma two comma three comma four five and that's an alternative to saying one to ten so if it isn't a continuous range of values which i'm testing that would be the way to go and i can use all of my relational operators when i'm composing a test as well so for example here i've used a less than sign but i could use greater than i could use less than or equal to greater than or equal to not equal to the same as if i was building a test for an if block now you might be wondering why bother with an if block at all why not use select case every time well there is a particular limitation when it comes to select case you can only test one variable at a time let's say for example we've also captured the wind speed i've just hard coded a value for the purpose of demonstration i can't do something like this with a select case construct i'm testing the contents of two variables using a logical operator with a select case construct i can only test one variable at a time i could however nest an if block inside the select case construct something like this so if the temperature is less than zero we'll report that it is sub-zero and then we'll check the wind speed and if the wind speed is bigger than 20 we'll report that it's going to feel really cold you'd like to give it a try yourself maybe rewrite the exam grading program to use a select case construct instead of an if block by the way different programming languages might well have their own equivalent to the select case construct c sharp for example uses the switch construct but it does pretty much the same thing if you see pseudo code on an exam paper it may well be written like this i've commented it out because it won't work in visual basic but you can see the concept is pretty much the same i'm going to show you the third of the three fundamental constructs of high level programming namely iteration it's iteration means executing a block of code repeatedly iteration is also known as looping and there are two ways you can do this in vb.net one of them is with a for loop and the other is with a do loop in this video i'm going to focus on the for loop i've already created a new windows forms application and i've placed a button on the form so let's get right into the code to make something execute repeatedly i need a way to count the number of repetitions i need a way to count the number of iterations so i'm going to declare a variable of type integer it doesn't really matter what i call the variable i've called it i count because i'm going to count my way through a loop the for loop looks like this any code that i write between for and next will execute repeatedly in this case five times because i'm counting from one to five let's begin with a simple message give it a try hello once twice three times four times five times now that was a single line of code but let's put a couple more inside the loop try it again hello how are you well i hope once hello how are you well i hope twice so these three lines of code are executing in sequence five times let's take it back down to one line for now i can display the value of i count as part of the message like this hello1 hello2 3 4 5. let's do something a little more interesting my program will beep every time we pass through the loop the beep command is very straightforward threading.thread.sleep means pause for three seconds something nice about a looping construct such as the for loop is i can change the number of iterations as easily as this the code inside the loop will now execute 50 times i can also change the step value like this so i'm going to count up from one to fifty five at a time perhaps it makes more sense to count from zero i can also count backwards in this case i'm counting from 50 to zero and i'm stepping minus five at a time if i want to display the output in a single message box rather than separate message boxes i could do something like this inside the loop i'm not doing any output i'm simply building the output string i'm saying let st out equal whatever it used to be and then something else in this case the value of i count along with a new line operator this time i only have one message box outside of the loop and that's quite a common technique so there it is the for loop in the next video we'll look at the do loop and then following that you'll see how the looping constructs really come into their own when working with array variables before we move on and look at another iteration construct i thought it would be a good idea to get some practice in with what you've already learned i've written a program here which makes use of an if block and a couple of for loops i'll show you what it does first then you can pause the video and try to write it yourself when you're ready you can look at my solution my button has the text count up od or even because that's what it does let's see first i'm asked what number do you want to count up to i'd like to count up to 10. then i'm asked do you want odd numbers or even numbers notice i'm using an input box here you've seen this in an earlier video i want the even numbers and my program comes back with 2 4 6 8 10. let's run it again what number do you want to count up to i can choose any number i like i'll go with 10 again odd or even numbers let's try the odd numbers this time 1 3 5 7 nine and that's it let's just give it one more try let's count up to 20. odd or even let's go with odd again so that's the idea if you want to try writing this program yourself pause the video now and give it a go and then you can resume the video when you're ready to see my solution i should say there's no one way to solve this problem and here's my solution i've declared a variable called imax which is the number the program will count up to it's an integer variable i've declared a string variable called st odor even which will store order or even depending on what the user types in and then i have another variable called x which will be my loop counter it'll control passage through the count controlled loops i start by asking the user what number they would like to count up to that value gets assigned to imax then i ask the user do you want odd numbers or even numbers and that gets assigned to st odd or even i now have an if block where i'm testing the value of st odd or even if the user typed in even then we have a for loop which will count up in even numbers notice that i'm starting from two and counting up to imax and i'm using the step clause to say that i want to step two at a time so that's going to give me the even numbers up to the number that the user types in else if st odd or even is equal to odd then i have a for loop which starts at one runs to imax but also steps two at a time so we start with one then we add two then we add two and so on as i said this is just my solution you might have come up with something slightly different for example you might have used two separate if statements like this and that's fine because it will work having said that using a single if block with an else if clause is a little bit more efficient because this program will have to perform both tests did you get something similar did yours work if not why not try my approach you previously saw how to make a line of code or indeed a block of code execute repeatedly using a for next loop like this one here i'm using a variable which i've named x to count my way through the loop let's just remind ourselves what it does personally i tend to avoid using letters of the alphabet for variable names i like the names to be a little bit more meaningful so i'm going to rename x to something a little more appropriate i've called it i count instead i because it's an integer and count because that's what it's for it's to count my way through the loop in this video i want to show you an alternative way to make a line of code or a block of code execute repeatedly i'm going to show you something called the do while loop i'm referring to it as the do while loop because most people do but as you'll see in a moment it comes in a number of different forms here's one of them now you might be tempted to give this a try as it stands i strongly recommend that whenever you're writing code that contains looping constructs you should always save your code first watch what happens when i run this hello hello this will go on forever just saying hello zero let's see if we can work out why i need to stop the program fortunately i can still see this red square here so that will force the execution to stop i've said that i want the loop to repeat while the value of i count is less than or equal to five immediately after you've declared a numeric variable it will contain zero so by the time we get to this line of code i count contains the value zero which of course is less than or equal to five so we output hello zero when the loop repeats i count is still zero its value hasn't changed so we output the message again and then the loop repeats again and again and again it's called an infinite loop it will go on forever because i'm using a do while loop i need to make sure that i write some code to increment the value of i count i'm going to increment the value of i count before i do the output like this so all this line of code says is take the value of i count add one to it and then put the result back into high count overwriting what's already there in other words add one to i count so at the top of the loop we check if the value of i count is less than or equal to five which first time around it is it's equal to zero then we increment it so now i count has the value one then we do the output hello one we go back to the top of the loop and because i count is still less than or equal to five we get back into the loop code and we add one to it highcount now has a value of two so we can output hello2 and around and around we go until such time as i count is no longer less than or equal to five we've met the so-called exit condition of the loop so we can exit the loop and the program will continue down here let's just put a line of code in here just to prove that the program has dropped out of the loop now let's give it a go hello one two three four five six we'll have to look at that and think about why that's happening and then all done i only wanted to count up to five but it actually counted up to six and that has to do with the exit condition of my loop i said i want to loop while i count is less than or equal to five which means my loop will continue if i count is equal to five when i count is equal to five i add one to it so it becomes six and i do another output all i need to change is that exit condition do while i count is less than five that's better you need to be mindful of the contents of the variable which you are using to count your way through the loop now you might be wondering why do we bother with do while loops when we have four next loops i've had to write more code to get the same effect the answer to that question is that the do while loop is more flexible for example i can say do until i count is equal to five strictly speaking this is not a do while loop this is a do until loop watch what happens when i run it exactly the same effect but it means that i can build an alternative exit condition for a loop and as you'll see later sometimes it's more appropriate to use do until rather than do while i can also do this i'm just going to move this piece of code so i'm saying do this block of code and loop until i count is equal to five let's take a look exactly the same effect but sometimes it's appropriate to put the exit condition at the bottom of the loop this means that the code inside the loop will execute at least once if the exit condition is at the top of the loop it might not execute at all if for example something has set the value of i count to be equal to 5 before we go into the loop like this then the code inside the loop won't execute at all we've already met the exit condition and there's one more form of the do while loop if i may call it that which i'd like to show you loop while i count is less than five does the same thing let's look at those four variations next to each other so we can compare them for loops that do exactly the same thing now we need to be careful here i need to re-initialize the value of i count in between each of these loops it starts off here with a value of zero but by the time we've dropped out of the first loop it will have a value of five as i said you need to be mindful of the value inside the variable which you are using to count your way through the loop for good practice i'm going to explicitly initialize it here as well although i know in this particular program it will have a value of 0 at that point so there you have it four different variations of the do while loop or the do until loop if you'd rather call it that i'm going to show you a useful application of a do while loop i want the user to enter a number and only a number a do loop can be used to repeatedly prompt the user if the data is invalid i'm also going to show you why a do loop is called a condition controlled loop you might remember that a for next loop is called a count controlled loop let's write some code let me show you something which might strike you as rather silly but it makes a very important point i'm using an input box function to prompt the user to type in their name but the name must be kevin so i've placed this instruction inside a do while loop and look at my exit condition do while st name is not equal to kevin when we drop out of the loop i simply output the name that was entered let's give it a try i'll try john that's no good ben nope enzo anything i type is invalid unless it's kevin you can see why this is called a condition controlled loop rather than a count controlled loop i'm not incrementing a variable to determine how many times i pass through the loop there's no loop counter involved let me show you another approach do while true equals true i could have just as easily said do while one is equal to one that might strike you as a rather ridiculous exit condition because one always equals one essentially what i've written here is an infinite loop true equals true is more typical in fact i can just say do while true it means exactly the same thing but if i have an infinite loop well how do i get out of it i can do this i capture the input test it to see if it's what i'm looking for and if it is then i force an exit from the do loop by using the command exit do once again you can see that i'm not counting my way through the loop i'm exiting the loop in a different way so how is all of this useful well as i said i want to write a program to prompt the user to enter a number and only a number take a look at this i've declared two variables one called sth because i want to capture the user's age but notice i've declared it as a string and then i've declared another variable called i age which is an integer i'm prompting the user to enter their age and i'm assigning the value to sth this is a temporary measure so that i can test sth and look at my exit condition do while is numeric sth equals false in other words while whatever the user types in cannot be converted into a number to understand this you need to appreciate that the input box function always captures a string so for example if i'm prompted to type a number and i type let's say 59 i'm actually typing the string five nine if i attempt to assign that string to a numeric variable like i age it'll be fine visual basic will do something called implicit type conversion it will automatically convert it into an integer because it can for example this line of code will be absolutely fine as long as the user types in a string that can be converted into an integer if however when this line of code executes the user types in a string like hello it will crash the program because visual basic can't automatically convert that string into something we can save into an integer variable i'm trying to prevent my program crashing for that reason so instead i'm asking the user to type in their age but i'm storing it into a string variable it doesn't matter what they type when we assign it to a string variable it'll work but because i want a number i keep asking the user to type something until such time as i can convert it into a number and that's what is numeric is telling me whether or not a variable's contents can be converted into a number i could ask the same question in a slightly different way like this for example do while is numeric is not equal to true it means the same thing as do while is numeric equals false i can even ask the question like this do while not is numeric it's the same exit condition just phrased in a different way i'm using a logical operator this time instead of a relational operator it really is a case of take your pick so we are repeatedly prompting the user to type in something we can convert into a number and when the user finally types in something that we can convert into a number we do so i'm using one of the type conversion functions this time c int that's short for convert to integer so i'm converting this string into an integer and i know that this line of code is not going to crash because we wouldn't have got this far in the program unless the user typed in something that i could convert this is called explicit type conversion it's also called casting when we change the data from one data type to another let's give it a try i'll start with some text that's invalid so i'm being prompted again let's try some different text again i didn't type something which can be converted into a number so the loop continues let's try typing nothing at all i'll just click ok well that's no good either because that's what we call a zero length string think of a pair of quotes with nothing in between if i press the cancel button again that's invalid i can't get out of this until i type something that can be converted into a number remember that might look like 123 but it's actually the string one two three but it's a string that can be converted into a number so we drop out of the loop convert the input into a number store it in ih and then display it in the message box so there you go a condition controlled do while loop which i'm using to capture input and validate it at the same time in this video i'm going to talk about array variables as you'll see array variables are particularly useful when you want to store a large number of related data items in fact once you've learned about array variables you'll be able to write some very very useful programs before i begin let's quickly review what's going on inside the computer's memory when we use regular variables when this line of code executes the operating system will set aside a piece of memory and it will give it the name s t fruit the exact location of this piece of memory is entirely up to the operating system it doesn't really concern us as programmers but suffice to say no other program can use that piece of memory it belongs to this program immediately after a string variable has been declared it will contain something it contains a zero length string think of a pair of double quotes with nothing in between them if you declare a numeric variable for example an integer then immediately after declaration it will contain the value zero for the purposes of this discussion we don't really need to worry about this zero length string when this line of code executes i'm assigning a value to the variable i'm putting the text banana in there when i output the contents of a variable it doesn't change the contents of the variable we're simply taking a copy of what's in the variable and then displaying it on the screen my variable still contains the text banana this line of code will overwrite the existing contents of the variable we're replacing the text banana with the text orange the original contents of the variable are now lost when this line of code executes a separate piece of memory is being set aside this time the piece of memory is called st fruit 2. no prizes for guessing what that's going to be storing the exact location of this second variable again depends on the operating system one of the main functions of the operating system in my case windows 10 is to manage the memory this line of code assigns the string pineapple to st fruit 2. when this line of code executes a copy of the contents of st fruit are assigned to st fruit 2. so orange overwrites pineapple by the time we get to the final message box statement both variables contain the same thing now let's talk about array variables suppose that i want to store and process several different items of fruit i could do it like this i've declared five separate variables and i've initialized them individually if i want to output the contents of one of those variables that's straightforward enough as long as i know the name of the variable that will output pineapple but using regular variables like this to store a group of related data items is actually quite cumbersome what if i wanted to store 10 items of fruit or even 100 items of fruit i'm going to end up with rather a lot of code instead of using five separate string variables i'm going to use one array variable like this i've used quite a lot of copying and pasting to speed things up i'm also going to change the name of this variable just to indicate that it is actually an array variable i'm going to prefix the name with hey a because it's an array st because it's an array of strings and fruits because well that's what these are you could actually call your array anything you like but as you write more code you'll see the benefits of a naming convention to understand what's going on here again we should visualize what's going on inside the computer's memory when i declare an array variable like this i'm actually saying that i want to set aside a group of memory locations to be more precise i'm setting aside a group of contiguous memory locations contiguous means adjacent next to each other the number four means that i want a group of five memory locations it might strike you as odd but in computer science we generally count from zero we say that the array is zero based each location in that group of memory locations is referred to as an element so i have five elements numbered from zero to four when this line of code executes i'm putting the text banana into element zero this line of code puts orange into element one pineapple into element two strawberry into element three and mango goes into element number four i'm referring to each element by its index number when i want to reference one of those data items again i use the index number so in this case i'm outputting the contents of ast fruits 2 element number 2 pineapple let's give it a try as expected let's output orange i just have to change the two to a one if i want to output mango i'll type a four here i can also reference an element of an array less directly let's declare an integer variable i'm just giving it the name i i'm going to assign a value to that variable and now i'm going to use the contents of i to reference an element of the array can you see what the program will output this time i is equal to 3 so this reads as ast fruits 3 it will output strawberry indeed it does let's change the value of i to 0. now i'm out putting banana banana is the zeroth element of the array we can run into trouble though watch this i'm setting the value of i to be equal to eight my array variable only has five elements numbered from zero to four there is no element number eight so what happens when i run the program now index out of range exception my program has crashed it's crashed because it can't find element number eight there's no such thing let's reset the program now there's one more thing i would like to show you which is where the real power of array variables comes in i want to output each of those items in turn so i am going to iterate through the array using a for next loop watch this for i equals naught to four output ast fruits i first time through the loop i is equal to zero so this will output banana second time through the loop i will be equal to one so we output orange then i is incremented to two and we output pineapple and so on until such time as i equals four let's give it a try and you can imagine i can iterate through a hundred array elements just as easily as i can iterate through five give this a try yourself perhaps you can set up an array with ten elements instead of five in this video i'm going to invite you to practice what you've already learned there are eight exercises here involving array variables and loops which you might like to try coding up yourself i'll show you what they do and then it's up to you if you want to give them a go alternatively you can jump straight to my solutions later on in this video by the way all of these programs start with the same six lines of code all of them declare an array variable of integers with five elements and then the array is initialized as you can see here but it's important to realize that your programs have to work with any data not just these so let's see what they do the first exercise is to output each item in a separate message box one after another well you've already seen how to do this in a previous video i'm using a loop to scan through the array exercise 2 output all of the items in the same message box but on separate lines exercise three is to add up all of the items and output the total in a message box they add up to seventy five in exercise four we calculate the average of the items the average value is fifteen very similar to exercise three except we're dividing the total by the number of items in exercise five we are only adding up the items that are bigger than twenty there are two items in the array which are bigger than twenty namely thirty three and twenty two and they add up to fifty five we're still doing this with a loop but as we visit each item we're deciding whether it's bigger than 20 or not in exercise six this is a little bit trickier you have to find the largest item and output it in a message box the biggest item is thirty three and let's be clear the program is working out which is the biggest item if you can do exercise six you'll find exercise 7 very easy exercise 7 is finding the smallest item and exercise 8 is replacing each item in the array with a new value that is twice as big and then we output those values in pretty much the same way as we did in exercise two so if you want to give them a try yourself pause the video now and see what you can come up with alternatively you can jump straight to the solutions so let's take a look at my solutions the objective of exercise one was to output each item in a separate message box one after another you've seen how to do this in a previous video i start by declaring an array of five integers and then i initialize the array in order to scan the array i need a loop counter so i've declared an integer variable called i and that controls the number of passes through the for loop then i say for i equals naught to 4 output ai data element number i so first time through the loop i is zero that outputs the first item second time i is one i output the second item and so on until i is equal to four we output the last item and we drop out of the loop in exercise 2 we want to output all of the items in the same message box so we don't have an output command within the loop we're simply building a string i've declared a string variable called st out and inside the loop i say st out equals whatever it used to be plus the next item in the array i'm also concatenating a new line operator on there as well so the string actually contains the information needed to throw a new line between each item when we drop out of the loop we display the output string in one go the solution to exercise 3 is similar to the solution to exercise 2. we want to calculate the total of the data items so i've declared a variable called i total to contain this and then as we visit each item in the loop i say i total equals whatever it used to be plus the next item i'm using the addition operator instead of the concatenation operator this time when we drop out of the loop i display the total in one message the objective of exercise 4 was to calculate the average well this is pretty much the same as the previous exercise i calculate the total first and then when i display the message i simply divide the total by five with exercise five the objective was to add up all of the items bigger than 20. so in some ways it's similar to the previous program i've declared a variable to hold the total but look what's going on inside the for loop i'm adding the next value to the total conditionally i'm testing each value first to see if it's bigger than 20 and if it is i add it to the total if it isn't well i don't if you think about it adding up all of the items which are let's say smaller than 20 would require a very simple change all i'd need to do is change this relational operator to a less than sign in exercise 6 you were invited to write a program to find the largest item in the array the principle behind this program is to visit each item in the array and if it's bigger than the previous item then keep a record of it so i've declared a variable called imax which will hold the maximum value and i've initialized it to zero which pretty much guarantees that everything is going to be bigger than imax to begin with assuming i'm only working with positive numbers when i visit the first item inside my loop i ask is it bigger than i max well of course item zero the number five is bigger than imax it's bigger than zero so i'm assigning the first item to imax overwriting its previous value imax now contains a five five is the biggest item we've found so far second time through the loop i examine the second item and i ask is it bigger than imax in this case well seven is bigger than five so i replace five with seven i'm keeping track of the biggest item third time through the loop same question and i replace seven with 33 but fourth time through the loop i find that 22 is not bigger than 33 so this line of code doesn't execute by the time the program's finished imax contains the biggest value if you can solve exercise 6 then you can solve exercise 7 very very easily this time i have a variable called i min which is going to hold the minimum value and i'm initializing it with a very large value something that i know is bigger than anything else in the array i've made it ten thousand when i visit the first item i ask is it smaller than i min well of course it is 5 is smaller than 10 000. so i min becomes the first value and then we proceed pretty much as we did in the previous program by the time we drop out of the loop we have the smallest value the objective of exercise eight was to replace each item in the array with a new value twice as big i actually want to change the contents of the array and that's what this loop does it's actually very simple i say let a i data the item i'm looking at be equal to itself multiplied by two so by the time we drop out of this loop the array contains a completely different set of data and then the remaining code simply outputs those data in a single message box just like in exercise two now even if you didn't solve these problems yourself it's well worth trying to duplicate the code that you can see here it will definitely help you get a feel for using array variables with loops in this video i'm going to show you how to implement a linear search a linear search is one of many standard algorithms that you'll come across as a programmer the principle of a linear search is to examine a list of items one at a time to see if it contains an item that we're looking for i've already declared an array of ten strings and you can see i've initialized it with various items of fruit by the way you can see that the program contains the data that we're going to search we say that the data has been hard coded into the program this is untypical in reality a program wouldn't normally have the data written into it like this you'll see in later videos that a program can actually read the data in from an external file perhaps a database or a text file or a spreadsheet or even a web page you'll also see how one program can call another and pass it some data to work with for the purposes of demonstrating a linear search hard coding the data like this is absolutely fine we'll start by prompting the user for an item to search for we'll call it the target value so i've declared a variable to store it and to keep things simple i'll use an input box to prompt the user now i'm going to use a loop to scan through the array to visit each item one at a time i'll need a loop counter and i'm going to use a for loop i could use a do loop it's a matter of preference a for loop will mean i can write slightly less code as i visit each item i'm going to check to see if it's the target value i can do this with an if statement now this isn't the finished product but it's well on the way let's see what happens i'm getting a message for every item which is not the one i'm searching for but i did get a message saying it found it let's try it again i'm looking for a star fruit this time there is no star fruit in the list well it's on the way but i don't want a message for every item which isn't the one i'm looking for so let's improve it rather than doing some output inside the loop i'm simply going to keep a record of whether or not i found it and to do this i'm going to use a boolean variable a boolean variable can have one of two possible values true or false immediately after it's been declared it'll have a value of false so inside the loop if i find what i'm looking for i'm going to set b found to be equal to true and i don't need an else clause because if we don't find what we're looking for b found will never get set to true and when we exit the loop b found will still be false all that remains to be done now is to test be found once we get out of the loop to see if it's equal to true let's see what happens we'll start by looking for something that we know is in the list found it just one message let's try again we'll search for something else that we know is in the list yes there's a fig what about something that isn't in the list not found now just a couple of words of warning when you're comparing strings in vb.net string comparisons are case sensitive so for example if i search for banana with a small b not found however banana with a large b is found you've seen something similar to this in an earlier video i can remove the case sensitivity of a string comparison like this so i'm comparing the uppercase version of the target with the uppercase version of the array item i can achieve exactly the same effect like this l case means lowercase so i'm comparing the lowercase version of the target with the lowercase version of the item in the array and it's probably worth mentioning this as well i can use dot 2 upper instead of u case now there's one more improvement i can make to the efficiency of my program if i find what i'm looking for there's no point in examining all of the other items in the array if b found gets set to true then we can force an exit from the for loop for example if we're searching for apple and we set b found to true there's no point in looking at all of the other items in the array we already know it's there so there you have it a standard linear search if you're going to write code to create and manipulate a two-dimensional array variable it's essential that you can visualize the data you're working with very often a two-dimensional array variable is used to store groups of related data items like the data you can see here a two-dimensional array can therefore be thought of as a table these are the data we're going to use in this video each row of the table contains the details of a different famous person the first column contains their first names the second contains their last names the third column is gender then we have nationalities and finally their occupations what it is each person is famous for notice that each column has an index number counting starts from zero so the fifth column is column number four each row also has an index number and these are also numbered from zero it's useful to think of this table as having a horizontal dimension which we'll refer to as the x dimension and the vertical dimension which we'll refer to as y just like the x and y axes of a line chart when you're coding up a two-dimensional array for a different set of data i strongly recommend that you keep a sketch of it handy like i'm going to do now i can declare my two-dimensional array variable like this i'm using a naming convention here a because it's an array variable st because it's an array of strings and people because that's what the data is in brackets i've specified the x dimension first followed by a comma and then the y dimension and i've used the as clause to specify that this is an array of strings now i'm keeping my sketch of the data handy while i populate this array it's important to get this right otherwise you might get some very peculiar behavior when you run your program i want to put barrack in the first column and the first row i want obama in the second column and the first row the third column first row contains mail and column number three row number zero contains american it takes a little bit of getting used to counting from zero and the final piece of data for this person is president now it's tempting to start copying and pasting but i want to make sure i get this absolutely right so i'm going to continue entering the values individually just for now working from my sketch let's get the new zealand prime minister in next as with the previous famous person i've specified the column number first followed by the row number i've specified x followed by y notice that the value of x is different for each data item but the value of y is always the same because y is the row number let's do one more very carefully and then i'll speed things up with a bit of copying and pasting and i've just realized that i've made a mistake it's very easy to do that's more like it now you could initialize each individual element of this array in any order you like the important thing being that it's fully initialized but taking a systematic approach like this will help to ensure if not guarantee you won't make any silly mistakes a systematic approach will also help to ensure that all of the data gets in there but i can see a pattern emerging now so i'm going to start copying and pasting to speed things up a little bit now one last look at my sketch just to make sure i've got everything there that should be there and straight away i can see i need to change these twos to fives and there it is the code i need to declare and populate my two-dimensional array so that's how we get data in how do we get data out it's actually very simple if you've ever played a game like battleships with this message box statement i'm going to output whatever is in column 4 row three in this case the word scientist what if i want to output let's say new zealand that's in column three row one or perhaps the word swiss that's row three column three it's just a matter of supplying the appropriate coordinates i can also supply these coordinates using variables now i could call these variables anything i like but it makes perfect sense to call them x and y can you see which data item will be output by this message box let's see now just like a one-dimensional array the real power of a two-dimensional array is realized when you combine it with looping constructs let's suppose i want to output all of the information about barack obama notice that with barack obama it's the x dimension which is changing from zero to four but the y dimension remains at zero i can do this in fact i don't even need the variable y suppose instead i want to output the details of mahatma gandhi again it's the x value which varies but the y value stays the same in this case y remains at four you should make sure that you're comfortable with this idea before you continue let's try ada lovelace ada lovelace is in row number two so the value of y has to remain the same inside this loop it has to be two alternatively i might decide that i want to display all of the values in a particular column for example i might want to display all of the last names if we examine the data we can see that every last name has the same value of x obama is one zero ardern is one one lovelace one two einstein won three gandhi is one four and van gogh is one five it's the value of y which is changing this time so i could write my loop like this but notice that y varies from zero to five so this time it's the value of x which is remaining the same inside the loop but y is the value that changes perhaps i want to display all of the nationalities looking at the code i can see that all of the nationalities have an x value of 3. again you should make sure that you're comfortable with doing this before you proceed in the next video i'll show you how we can get all of the data out using nested loops in this video i'm going to show you how you can systematically visit each and every item in a two-dimensional array as in the previous video i recommend that you keep a sketch of your data handy to help you visualize what's going on here's a sketch of the data i'm working with you may for example want to display all of the data items one at a time row by row like this the data are being visited one whole row at a time but as each row is visited every column in the row is visited we say that the data in the array are being visited row wise here's what the output of a program that does this looks like alternatively you might want to visit the data column wise like this a program that does this deals with one complete column at a time but as each column is visited all of the rows in that column are visited and here's what the output would look like if you can systematically visit all of the data items in an array one way or another then you can collect the data into a single output string then output everything at once like this visiting the data also allows you to search for something in particular for example you can ask the user for a surname and then find all the details of that person like this so let's take a look at some code and see how this can be done i'll begin by writing some code to display the data row wise i've already declared the array and i've already initialized all of the elements of the array just to speed things up this is the same data which you saw in the previous video i need two loop counters because i'm going to use nested for loops if i want to visit one row at a time i need a for loop like this because each row is numbered from zero to five but while i'm visiting a particular row i want to visit each column and i can do it with a for loop like this the columns are numbered from 0 to 4. think of it this way for each pass of the outer loop there will be several passes of the inner loop and now i'm going to output a data item for each pass of the inner loop let's see what happens when we run the program now let's display the data column wise i'm using a different button to run this program but i'm going to copy and paste some code it's the same code i used to declare and initialize the array in a later video i'll show you how two different procedures can share the same data for now we'll proceed like this to visit the data column wise i'm going to use nested loops again but this time i'm going to scan the columns primarily so i'm going to scan across the x dimension using my outer loop and as i visit each column i'm going to visit each row within that column and i need another message box as before let's see how it looks this time to display all of the data in a single message box i need to decide whether i'm going to build the output string in a row-wise fashion or a column-wise fashion i'm going to do it row-wise so again i'm going to borrow some code this is the code that displays the data items individually but column wise i need a string variable to collect the data into and then rather than displaying a message box for each pass of the inner loop i'm going to concatenate some new data to the output string and between each data item i'd like a space because i want each row of data to appear on a separate line within the message box i'm going to concatenate a vb new line character onto the output string but only with each pass of the outer loop and once the nested loops have both finished i can do one output with a single message box let's see if it works the final thing i want to show you is how we can search for the details of a particular person based on their surname for example i don't actually need nested loops to do this i'm going to use the same technique which i showed you in the previous video let's start by declaring and initializing the array and i need some loop counters and i'm going to use a boolean variable to record whether or not i found what i'm looking for i'm going to initialize it as false although to be honest i don't need to do that because immediately after it's been declared it will have a value of false i just want my code to be explicit i'll prompt the user for the target surname using an input box just to keep things simple so i'm going to need a variable to hold the target value i know that the surnames are in column number one so i'm going to write a loop to scan down the rows of column number one only testing each value as i go notice how i've hard coded the value of the x dimension here i'm always looking at column number one as i scan down the column if the data item which i'm looking at matches the target then i'll set my boolean variable to be equal to true and i can force an exit from this for loop by the time i've dropped out of the loop i know whether or not i've found what i'm looking for if i have then i can retrieve the rest of the data for that particular person notice this time i'm scanning across the row the value of y will be whatever it was when the first for loop came to an end so i know this loop is looking at the correct row if b found was equal to false then we simply display a message saying that we can't find what the user was looking for there's one final thing we need to add to this code let's see it in action that seems to be working fine and just to be sure let's look for somebody who isn't in the array that looks okay as well having said that we have an additional message box here which is rather untidy let's put this right that's better you should try writing some of these programs yourself perhaps you could display the data column wise but within the same message box or maybe build a search facility where you enter the person's occupation to retrieve all of their details
Info
Channel: freeCodeCamp.org
Views: 517,102
Rating: undefined out of 5
Keywords:
Id: HFWQdGn5DaU
Channel Id: undefined
Length: 197min 19sec (11839 seconds)
Published: Mon Jun 13 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.