While Loops - C# Mastery Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in the last lesson we learned about even else statements and how we use them to partially solve our requirement to continue to ask the user for their date of birth the if and else statements are however one-time evaluation statements if this then do that they are not loops or recursive we partially solved our requirement by creating a recursive loop whereby we call the same function over and over however i explained why this is not the correct solution let's take a look at using while loops to create a true loop without recursion to solve our requirement correctly the current logic of this method is that we ask the user for their date of birth and then if they enter the date correctly we return the value otherwise we tell them they didn't enter the date of birth and we run this method again which effectively asks the user again this recursive loop works but it suffers from the recursion problem and the stack overflow instead let's use a while loop let's see a while loop in action and explain it go to the top of the main method and let's write a while loop you will notice this looks similar to an if statement we have our keyword this time while instead of if then we have our parentheses that expects an expression that evaluates to true or false and then we have the code block that will run syntactically this is exactly the same as an if or else statement the only difference lies in what happens when the value is true if the value is false this is exactly the same as an if statement let's debug our code and see that in action place a breakpoint on the while statement press f5 to run the code press f10 to step over the while statement evaluation and as you can see when it evaluates to false the code block is ignored and the next line of code is run the difference comes in what happens when the value is true let's change our full statement to true press f5 to run the program again press f10 to evaluate the while statement and this time it is true notice how we enter the code block just like an if statement press f10 to run through the code block and if this was an if statement the next line would jump to here because the if statement is evaluated but watch what happens with a while loop the code jumps back up to the while statement and reevaluates this expression again as it's true again the code runs again and this loop continues until this expression returns false in this case it never would so we have an infinite loop let's take a look at our call stack and you can see our call stack is clean there are no continuing call stacks adding up this is because we have no recursion inside this loop calling the same method this loop is within such as main we can prove we have no stack overflow recursion issue by removing the breakpoint and pressing f5 and letting the program run you can see the scroll bar flying down and an indefinite amount of heart is written out this program won't crash there's no memory leaks the memory staying the same and it's simply calling this code over and over as fast as it can typically we don't use infinite loops although we do use them for some things it's more common to use them similar to an if statement to repeat a task until the expression is satisfied let's modify this code and run the code until a variable is false now let's run this code again and step through it line by line we can see that my variable is true as in the locals window so this will evaluate to true the code block will run and here we now change my variable to false at the end of the while statement it jumps back up and it's going to re-evaluate the statement but this time the variable is false so now we have finished the while loop and we move to the next line of code the result of this while loop is that it will always run just once because the logic is static it is true at the start it runs without any other branching statements such as if or else there's no conditions it will simply always start with true run once be set to false and escape so this statement acts effectively like an if statement because it will only ever run once let's modify this further and let's say we wanted this loop to run until a number reached a certain value we will change my variable to an integer of zero and we will change this condition expression to say when the variable is less than 10. this code should make sense to you except for this less than statement that we haven't yet seen we create an integer called myvariable we give it a value of zero we have a while loop that is waiting for this expression to evaluate to true and will loop until it does and once it's false it will escape to the next line of code and the code inside now wants to increment this variable up by one so this plus plus as we've seen before takes the current value which on the first loop would be zero and adds one to it what will happen then is this while loop will check if the number is less than 10 this less than sign means that if the value on the left-hand side is less than the value on the right-hand side then the result of the expression is true otherwise it is false so a value of 10 less than 10 is always false because it's equal to it's not less than a value of 1 is less than 10 is always true so if we place my variable as the variable part of the expression this will be true when my variable is 0 1 2 3 4 5 6 7 8 and 9. once it gets to 10 this evaluates to false and we should come out of the while loop let's run that code to see it in action and confirm it does what we think it does we first check that 0 is less than 10 which is true and we say hi so instead let's actually output the value so this will be a little bit more useful so my variable 0 is less than 10 is true we've output the value that says the value is 0. we increment the value by one we check again one is still less than ten we now output the new value and you can see this loop continues until my variable gets to 10. now my variable is 10 10 and is less than 10 will be false and we escape to the next line and the output window is output the value is zero up to the value is nine and then we are done you may see this kind of block which is a common style of wire loops being shorthanded where the incremental value is placed in line so we would remove this and we can add my variable plus plus is less than 10. this works because the compiler is smart enough to allow you to do this incremental operator on the variable and compare the original value as part of the expression so 0 is less than 10 and then after the expression increment the value either way whether the expression was true or false so it's a little bit confusing to get your head around but what it effectively does is does the same check such as my variable is less than 10 and if it is true or false after the expression is run it then increments it by one this will give the result of saying while 0 is less than 10 now add an extra number so this will now be one and this will output one instead of zero if we run the code with f5 we can see here exactly that instead of it saying the value is 0 to 9 it gives us the answers the values are 1 to 10. this is because instead of outputting the variable and then incrementing the value here we have effectively incremented the value here in essence just remember that using this unary incremental operator produces different results than you may expect and you have to be aware of what is happening in the code don't worry too much about this style of loop for now i'm just showing it you because it is a very common pattern as well as some other pitfalls that people make when using it so now you have seen while loops in action let's use that knowledge to solve our requirement as mentioned our method would like to ask the user for their date of birth until a valid date is given let's start by creating a new variable called date of birth and giving it the value date time offset.max value so it is in the furthest future now we would like to loop until this value date of birth comes before the current date another way to say it is while the date of birth is greater than now [Applause] as in today the time right now as i showed you above with the less than sign we can also use the greater than sign to check if the value on the left is greater than the value on the right when we compare times and dates in this way we are comparing if the date on the left is before in time as in earlier in time than the date on the right if we run this code now we would be stuck in an infinite loop inside this while loop this code would never get run because the date of birth is set to the maximum possible time and now is never going to reach that time in our lifetimes if we put a breakpoint here press f5 to run the code we will see this date of birth is set to the year 999 and obviously now is 2020. so the year 999 is greater than the year 2020. so this loop will evaluate to true we do nothing inside the loop but it will continue over and over in theory if now ever reached the year 999 and got past that date which is actually impossible in code because max value cannot be greater than max value we would exit the code so what we have here now is an infinite loop that would never exit let's place all of our current logic inside the while loop let's interpret what would happen now the code would come down see that the date of birth is greater than now and it would enter the code block we asked the user for their date of birth and if it was successful we return the passed date the return inside of a while statement will escape the while statement just as running it from outside of the block would the return keyword from wherever it is inside the code block no matter what indentation level will short circuit right the way back out of the method this return will effectively force the code to skip over anything else and jump straight to the closing code block of the method and return this value from the method if however the date entered was invalid we would simply ask the user to enter it again and let's remove this return method this recursive loop because now we have a while loop so this code as it stands appears to work not because we have changed the date of birth variable to break out of the while loop but instead because this return value actually short circuits out of the while loop for us and if it was false then the while loop would run again causing the same style of looping until we get a valid answer where we escape from the method so in theory we could delete the date of birth variable and just change the while loop to a true loop and this code would act just the same so code like this would actually serve the requirements of this method perfectly so let's run this code and check that assertion and prove it as true place a breakpoint on the while loop press f5 to run the code press f10 until we ask for some date of birth press enter so the date is not valid the pause fails we ask the user for the date of birth we get to the end of the while loop it re-evaluates to true and asks us all over again we press enter a few more times and you can see it continues to loop but importantly the call stack is not flooded with additional method calls to ask for date of birth we have a clean call stack this method is inside of itself and not recursing it is simply looping inside of itself let's enter a valid date of birth and you can see we then return this value to the caller and our program is complete so if this is running as we expected and fully solves our problem why did i start by thinking about a variable called date of birth and a while loop that checks if it's not true well what if we wanted to do something inside of this method after we have a valid pass date perhaps we want to do extra validation on this date such as if the date of birth is over 200 years old or less than three years old it is insanely unlikely that this is a valid date of birth by somebody on the computer we might want to do extra checks on the limits or we might simply want to write something to the console right now we could do that by putting curly braces back around the if statement [Applause] and doing something in here so why don't i want to do that either it's because you end up for one putting the logic of something that is true after this expression midway in the expression itself and two because you start to have what's called nested ifs and nested code if we then need to check if this parse date is less than something else so for now let's just check it against itself pretend this check as if it's less than three years old and then perhaps you want to check if the date is greater than 200 years old you can see what starts to happen is we have the namespace then an indent the class then an indent the method then an indent the while then an indent the if then an indent you just get indentation after indentation and your code goes further off the screen as you're writing code it also causes a thought pattern issue where logically as you read through your code instead of a clear definition of if this is true or false we're then here and then something else true or false here and going in a nice linear pattern your brain has to interpret the code if this is true then this is true then if this is true if there's then an else here your brain now has to think if this is true and this is true and this is false then the code is down here it's not very linear in pattern and it's very hard to follow we can avoid this by making our code use the negative inclinations so instead of saying if something is true do something we tend to do if something is false exit out of the program or crash and otherwise carry on in the linear fashion the reason this works in code is because typically your code and methods should have one purpose in the case of this it should be asking for the date of birth so it should be fairly easy to do step by step ask the user for the date of birth until we get it after that the code can go here and check if it's less than three years old after that it could check if it's greater than 200 years old after that it could return the value so we can do it step by step without having to indent over and over by making our logic checks in this way so the way we will solve this is our while loop will be here to get a valid date and nothing more and after that we can do our other logic let's add back the date of birth variable and the check of whether the date of birth is greater than the time of now looking at our if statement if we got a valid result instead of returning that result let's set the date of birth to that value otherwise we write we did not enter a valid date notice here we can also reduce this code by removing the superfluous code block because there's now only one line of code in the else statement and now this code will say while the date of birth is greater than now ask the user for the date of birth the difference being when they enter a valid date we set that date to the date of birth given and this check will happen on the next run so something that could have happened in the last code that was invalid is no matter whether the date of birth was greater than now we were returning that value that meant we could have entered a date in the future meaning the date of birth is invalid and it would have returned from the function without that correct check so in fact our code before was invalid it did not serve the correct purpose instead this while loop is here and this extra check is now happening that even if they enter a valid date it's simply set to the variable and this while loop acts as a guard to check that that value is now actually a possible date of birth meaning in the past also because we're now not exiting the method with a return we have a problem that it's saying not all co-paths return a value that is because this while loop will run until we have a valid date of birth then after the code here is not returning anything so let's add return date of birth we are now returning the value that's stored in date of birth which based on this while loops logic will always be a date that is less than now otherwise it will be stuck in this loop so let's check this new code place a breakpoint on the while loop and run the application we step in and ask the user for a date of birth let's start with an invalid date of birth and we can see the loop still happens now let's enter a date in the future so two two two two before this would have returned from the function here and exited in this instance we set it to two two two two the while loop runs and even though we've set the value it is actually further in the future than today's date so the loop happens again let's enter a date in the past and we can see it now successfully passes the while loops logic and this is now false we continue to here and we return the date of birth to the caller this code is now identical in function to the code before with the added protection that we now have a valid date when we return and you cannot enter a date in the future with the key difference being we can now place our next if statement here instead of being deep inside the while statement inside a nested if statement here it means the flow of our code is much more linear and easier to read it may not seem really useful right now but it is important in the way you think of structuring your code and your logic your if statements your while statements and how you interpret your logic there are many different ways to do the same thing we could instead invert the logic of this if move this up here and this down here and flip the logic around so there are many ways to do the same thing in code and it's important to try and get as few nested elements as possible as well as the way we do logic in a certain way i will teach you through this course this method is now complete and serves its purpose we wanted to ask the user for a date of birth and until we got that date of birth they cannot proceed our application is useless if we don't have a date of birth so it makes sense to simply ask indefinitely until we get a valid date this completes this method and it's time to move on to now using the data given to output some statistics
Info
Channel: AngelSix
Views: 4,142
Rating: undefined out of 5
Keywords: c#, software, development, wpf, vue, vue js, animation, web design, wevb, .net core, asp.net core, free, open source, git, tutorial, beginners, real world, javascript, html, css
Id: 4oX0p-x-crc
Channel Id: undefined
Length: 23min 53sec (1433 seconds)
Published: Sat May 09 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.