Go For Loop Tutorial | GoLang Programming Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's going on welcome back to nerd academy i'm your host james and in this video we're going to get a bit loopy with loops and go so let's go now loops are commonly used throughout software engineering they are used to repeat a similar or the same block of code a certain number of times or when a specified condition is met there are three main types of loops you got your basic for loop you got a while loop and a do while loop a for loop is commonly used when you have a known number of objects that you're going to iterate through and do something on for example a collection of objects in a slice or an array where you'd perform similar actions on each of those objects in your slice or array a while loop is used when you have to repeat that same block of code a unknown amount of times until a condition is met example of this is user input and a cli until it's good or reading a file until you're at the end of the file a do while loop is basically the same thing as a while loop except it will run at least once where in a while loop the condition could actually be met before it's run versus a do while loop it will not check that condition until it's run at least once so go only has the four keyword it doesn't have the do or the while so if we need any of these kind of loops we have to implement it ourselves so all right let's open our code editor and take a closer look alright let's start with a very nonsensical reason to actually use the for loop so let's say you wanted to print hello to the console five times you could just type it out five times let's go ahead and copy and paste this so we got hello five times let's run that so we can see we get hello five times now instead create a variable n and we'll set that to five and then we'll make a loop and we use the keyword for and then we must initialize a value usually i for index or indices semicolon and then we're gonna check this is a condition so we must check i we're gonna do less than five and then semicolon then we have a post statement so either we're going to increment increment or decrement so in our case we're going to go ahead and increment so shorthand is i plus plus so that will take i add 1 and set it back to the value of i so once again that's a keyword 4 that and tells the go compiling we're about to do a for loop we're going to initialize our value in our case we're going to start at zero then we're going to check the condition if i is less than five we're going to go through this loop so then i'll go in here and whatever we put in here it's going to do it's going to go through the code and then post post statement is this i plus plus so after the first iteration of the loop it will become one and also let me touch on inclusive and exclusive here so inclusive would be i is less than or equal to five so it will go zero one two three four and five exclusive it will go zero one two three and four so easy way to remember that is inclusive is including the last number and exclusive is excluding the last number now we can print hello let's actually use our variable and let's run this again and we get the same thing that was nice about this if you had a program that was requiring you to print hello five times and let's say the spec changed now we can go in here and say oh we gotta we gotta do it ten times or maybe a hundred times or maybe a thousand times oh no now we want it back to just you know 14 times i don't know you have one variable to change you don't have to copy and paste everything but this is a very nonsensical reason to use a for loop so let's talk about scope now this variable i is not available outside of these curly braces so we cannot go out here and say hey what's the value of i again the ide error here it's an undeclared name we declared it here but it's scoped inside these curly braces so we can't we don't have access to it so if we wanted to do that let's comment that out we'll create i and then we'll do four as long as n is less than phi or sorry i is less than five we'll print hello again and then don't forget we need to increment let me put this here i this is the same as i is equal i plus 1. so now we have access to i outside of this for loop because we declared it outside of it so let's run this again use that variable don't hard code we put that 14 that's fine there we go now we got it five times and we see the value of i is five outside of the for loop but now we literally just created a while loop so in other languages we'd go while i is less than n as long as that's true we do some code in there but we don't have the keyword while all we have is a keyword for so this is basically saying for as long as i is less than n exclusive we're gonna do the code here and if you forget to increment i here this will run forever let's see what happens it's going to keep going and going and going until we want to hit ctrl c to stop it now you could do this way for a for loop if you need i outside but this is generally not what while loops are for they're used for when you have an unknown number of times you have to iterate so a good example is doing something like reversing a number so let's declare two variables we're going to have a number and a reverse number they're both be integers let's go ahead and get the number from the command line we haven't done that yet so that's uh we're gonna do a prompt so printf enter a number to reverse scan format scan so that will read in from the standard input and store it now we gotta pass in the address to number otherwise it won't update it so now the user inputted a number now we're gonna go through a little algorithm using a while loop to reverse the number so far as long as number is not equal to zero because if someone puts in zero we don't need to reverse it because reverse zero is going to be zero there's other edge cases like single digits the first thing we're gonna do is we're gonna take the number reverse set it equal to reverse times 10. then we're going to take the reverse we're going to set it equal to reverse plus the number modulus 10. and then finally we're going to take the number and we're going to set that equals a number divided by 10. we're going to print the reversed number i owe you an explanation of this algorithm because maybe you haven't seen this before but it's kind of fun to try to kind of figure out so on the first iteration recall then go ling if you declare something and don't really initialize it going kind of initializes some of these like basic types anyway so an integer will be initialized to zero so we'll say first iteration reverse is zero so we're going to multiply 0 by 10 is going to give us 0. on the second iteration it might make sense why we're multiplying by 10. and yeah let's go ahead and assume that number is 21. we'll keep it short and simple and then we'll then we'll run it and see what it does so first iteration we're going to take reverse which is zero we're going to add the number modulus 10. so in the case of 21 21 mod 10 should give us one so reverse now is 1. and now we're going to take the number and divide by 10. so 21 divided by 10 is 2.1 but we're storing this in an integer so it does not care about anything beyond the decimal point so we get 2. now it goes back up and checks the number if number is not zero it's two so it's not zero so it's gonna go through this iteration one more time so our second iteration remember reverse is one so we're gonna go one times 10 is 10. now our second iteration on this here so our reverse number is 10 then we're going to add 2 modulus 10 which will be 2 so now reverse is 21. and lastly second iteration here we're going to take 2 divided by 10 equals 0.2 but once again we don't care about anything beyond the decimal because we're storing this an integer it is zero now to x is this loop and checks us again and we're done with the loop so now it's just going to print this out so let's run it and see if we get i made a mistake talking about this didn't i yeah right here this should be 12. we're going to add 10 plus 2 and we're going to get 12 not 21. so if we start with 21 we should get 12. so let's run this enter a number we get 12. so the basic of this algorithm is basically shifting over a reverse number multiplying by 10 and then chopping off the last digit of our original numbers so we keep kind of shifting over and then adding that last digit from the front of the number from the i'm sorry from the back of the number to the front of the reverse number hopefully that makes sense and also important to note just like it kind of talks about in the last uh four basically while loop and visually you need that condition to become false so it can break out of the for loop or the while loop because you'll get an infinite loop but infinite loops are often used in programming actually because for instance web servers such as our http listen and serve i'm pretty sure that's going to be a forever while loop or forever for loop in the case of go game loops often use a while loop that uh an infinite loop embedded code will often use in infinite loops because you kind of set it up and then it should keep running and kind of interact with whatever it's doing and system and service processes and there's plenty of other other examples but it's kind of just the kind of ones i pull from the air so let's take an example of using a kind of infinite loop until we get good user input from a from the user so let's create a variable call this one num i know pretty creative so we're going to get user input again say hey just enter a number i didn't do this in the last one but we need to check for an error when we uh when we scan so i'm going to put the address the num in there so as you can see it returns an integer and an error so if you want to ignore any return values and go you just use the underscore okay so we do want to check for an error so if that error is not nil that means there was an issue and we want to try to get valid input from the user so we're going to do four and then just open our code block so this will run until we tell it we're done so we say guess what invalid input please enter a number and once again scan that num in so this time we're going to check if error is nil and we're going to do we're going to call break so what that does is exits the loop it's in so if this as long as the user keeps inputting bad data and it can't take this number from the user and put it into an integer and it says hey nope it's going to keep looping and once it's okay then it's going to break out of this loop so then just to test it out we'll say you entered no all right so let's run this enter a number let's enter hello yep now we got a issue here it's under 12. okay that is printing out a bunch of times let's see what we did wrong probably something to do with the return carriage just do print lines then a7 s three interesting okay well so it's me from the future i figured out what i did wrong i was just taking the input and scanning it so in our four little while loop here it was redoing the loop for every character i entered so the best way to do it is actually use string convert the method a t o i string to an integer basically so what we want to do instead we're going to still scan our input and we're going to store the number because atoi returns the integer and an error so this time if there is not nil will go to our we'll go to our infinite loop and then we'll say hey guess what you made a mistake we're going to scan the input again this time we're taking it as a string and we're going to try to convert again if the error is nil there's no error so we break out of the loop i also wanted to talk about continue because it slipped my mind so there's break which will break out of the loop and then there's continue which will say okay just go to the next loop immediately what we could also do is if error if there's an error we can just say continue i mean it's kind of nonsensical i mean it kind of doesn't really it's not necessary here because if there is nil it breaks otherwise it's just going to loop again but if you really needed to continue at any point in your loop you can just use the keyword continue and it will stop the current loop and go all the way back to the beginning so let's try it out now that we've got it fixed so we're going to enter a bunch of nonsense like hello hey it only only says it once and it goes back says hey please invalid input please enter a number so now we can enter 456 there you go and it enters 456. now looping through in a an array or a slice can be done with a for loop but there's an easier way so let me quickly show you the for loop so let's say we have an interesting slice called nums initialize with one two and three we can do four i equals zero i less than length of nums i plus plus and then we can just print out nums with i which gives us the into c that's why we use i usually in for loops gives the indices of the array nums there we go one two three but there's a much easier way so instead of that we just do four we have index num we'll set that equal to range of nums and then we can print f nums of our index equals the num so we go index and num so we run this again there you go so this range is a required keyword if you're going to do loop through a collection of objects such as slices or arrays and it returns the index and the basically the value at that index so if you don't need the index at all you can just do underscore and then we'll just print out the number again and basically the same thing and all right there you have it that's the basics of loops and go so if you made it this far in the video i want to thank you so if you do me a favor go ahead and hit the like button i'd really appreciate it it'll help out the algorithm so remember always keep learning and if you want to watch more about go watch this video right here and we'll see you in the next one [Music] you
Info
Channel: NerdCademy
Views: 182
Rating: undefined out of 5
Keywords: software development, software development tutorial, programming tutorial, go for loop tutorial, golang for loop tutorial, golang for loop slice, golang for loop, go for loop, go while loop, golang while loop, go while loop tutorial, golang while loop tutorial, golang infinite loop, go infinite loop, go programming tutorial, golang programming tutorial, programming, software developer, go loop over slice, go loop break, go loop continue, go for range loop, golang range loop
Id: _i9Okyq5VG4
Channel Id: undefined
Length: 15min 16sec (916 seconds)
Published: Mon Nov 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.