![]() |
Introduction to Loops with Java - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Coding (https://sinister.ly/Forum-Coding) +--- Forum: Java, JVM, & JRE (https://sinister.ly/Forum-Java-JVM-JRE) +--- Thread: Introduction to Loops with Java (/Thread-Introduction-to-Loops-with-Java) Pages:
1
2
|
Introduction to Loops with Java - Ex094 - 08-14-2016 ![]() Sometimes its necessary to repeat an operation multiple times, suppose you are making an application that will handle the data of all the students currently enrolled in a university, such data would not be of small quantity. Suppose there are 1000 students and you have to calculate the individual GPA of each student. Now if there were no loops, imagine creating 1000 variables for each student and then applying the formula on each variable, result? Really messy code and eating up useless space plus very time consuming. But since loops are here for help, you don't have to write that operation to calculate the GPA for each student, instead we apply a loop b/w the range 1 and 1000, the loop would repeat the formula for each student it self. In order to perform loops, programming languages such as Java have provided us with a set of looping statements. A loop statement allows you to repeat code (may that be a single line or a block) multiple times. In Java and most languages, loops require a condition, i.e. the loop keeps going on if the condition is being fulfilled and it breaks itself when the condition is not met, if you're getting confused at this part don't worry the examples that we will do next with each loop statement will clear it up. Types of Loops There are three types of loops in general, Code: FOR Loop It is to be kept in mind that the body of a loop is executed in a sequential manner i.e. the first statement in the body will be the first to execute, then the 2nd statement and so on. FOR Loop The syntax is: Code: for(initialization; condition; increment) { Initialization is the part where you declare the control variable and assign it an initial value, the FOR loop always first initializes the variable then moves to the condition. Remember that the initialization part ends with a semi colon. Code: for(int i = 0; condition; update) { Condition is the part which tells the loop either it should go on or not. If the condition is met, the loop continues other wise it will break it's execution and the control is transferred to the next statement that comes after the for statement. The condition is also preceded by a semi colon. Code: for(int i = 0; i < 2; update) { Update will update the control variable that it initialized in the first place, you can increment or decrement here, its up to you to decide. Code: for(int i = 0; i < 2; i++) { Before we dry run our for loop, The order of execution is: Code: 1) The Initialization takes place, variable i is created in the memory and assigned the initial value 0. Dry Run: Our for loop is: Code: for(int i = 0; i < 2; i++) { Code: 1) Variable with data type i is created and assigned the value 0 QUICK QUIZ: What changes should we do to print Hello 2 times if we initialize the variable with the value 1 (i = 1) WHILE Loop Sytanx for while loop is: Code: while(condition) { The while loop will keep executing as long as the condition is fulfilled. While loop has kind of sub types too depending on the condition you implement. Code: 1) Counter Controlled (Control Variable) As the name suggests, we use a counter to control the loop. We first initialize the counter variable then use it with the while loop in the condition. Code: int counter = 0; We've done the initialization and applied the condition but what we are missing is the Update part, Without the update we will not be able to change our control variable and the loop will go on for on indefinitely. Unlike the for loop, a while loop have multiple parameters, you have to introduce the update inside the body so each time when the body is executed, the control variable is updated too, Don't worry we'll check this out in the dry run test. Code: int counter = 0; Dry Run Now we shall dry run the counter controlled while loop we just created above, Code: 1) Counter variable with data type int and initial value of 0 is created Flag Controlled Loop We can also control our while loops using Flag variables, a flag is basically a Boolean variable which we can use to control the operation of our while loop. Since it's of Boolean data type, it can be either True or False. We initialize the flag with some default value lets say true, now while the flag remains true, the loop will keep running. Due to some change in condition, we alter the value of flag to false, the loop will then stop. Code: boolean flag = true; The above loop will print "Hello" once because the 2nd statement in the body is changing the flag to false while our condition was to run the loop as long as the flag variable remains true. Lets edit this code and try to print "Hello" 2 times. Code: int count = 0; Dry Run Code: 1) Variable with data type int and initial value of 0 is created Sentinel Controlled Loop This type uses a special value to control the loop, Suppose you want to take a list of names as an input from a user and you have assigned a special value that when the user inputs will end the input stage. Code: Scanner read = new Scanner(System.in); The sentinel value can be anything, here the ; (semicolon) is our sentinel value. In simple words the condition inside the while reads that continue taking input from the user as long as there's no ; encountered. Once the sentinel value is encountered the condition will become false and the while loop with break. The input reading from the user could have been implemented in the while condition but has been ignored for the sake of simplicity. Dry Run Code: 1) Scanner object is created with the name read DO..WHILE Loop The syntax for the Do While Loop is Code: do { The do..while loop is same as the while loop except the fact that the condition is checked after the body has executed, Hence the body is always executed once no matter what the condition is. Converting the same example that we did above to do...while, Code: int counter = 0; Dry Run Code: 1) Counter variable with data type int and initial value of 0 is created Congrats, you've reached the end of this tutorial. I hope you've understood about loops by now and remember PRACTICE PRACTICE AND PRACTICE. Regards, Ex094 Original Post: Procurity RE: Introduction to Loops with Java - BxxxxxD~~ - 08-14-2016 would you be able to help me with an issue I'm having with a loop in java? The problem is that I want a button to be able to start an infinite loop, and then end the loop when the button is repressed. But, because it is a loop that loops constantly, the program will freeze and the user will be unable to press the button again once it has been started. The second part of the issues is that the button needs to be pressed again to stop the loop, however whenever the button is pressed the loop will start. If you can help that would be great, but either way your tutorial is well layed out and pretty helpful. RE: Introduction to Loops with Java - Ex094 - 08-14-2016 (08-14-2016, 08:48 AM)BxxxxxD~~ Wrote: would you be able to help me with an issue I'm having with a loop in java? Hey, Threads aren't in the scope of this ttutorial but the reason your GUI freezes is because you aren't using a separate Thread. Since a single thread runs the Java GUI, the infinite loop won't allow it to render the button. Hence create another Thread, put the while loop inside it.. Try it and then report back RE: Introduction to Loops with Java - Mr.Kurd - 08-14-2016 really thank buddy. I will save this too. But always this confused of me. RE: Introduction to Loops with Java - typhoid - 08-14-2016 what about the enhanced for loop? Code: for (int value: array) { Code: for (Object value: collection) { RE: Introduction to Loops with Java - Ex094 - 08-14-2016 (08-14-2016, 11:21 AM)typhoid Wrote: what about the enhanced for loop? Didn't want to scare beginners with this shiz, Might cover in some other post.. RE: Introduction to Loops with Java - Nil - 08-14-2016 Nicely laid out. I've been working with Java for a few months but took a little break. This was a nice little reminder of the syntax and explained well enough for people first being introduced to it. RE: Introduction to Loops with Java - The_Joker - 08-14-2016 Very well done! If you're planning on continuing or making this a series, please do! RE: Introduction to Loops with Java - Inori - 08-14-2016 Very well done; good explanations all around. Also, AAAAAHHH! YOU'RE BACK! WHERE THE HELL HAVE YOU BEEN FOR THE LAST 2 YEARS??? (it's Ruby, if that rings a bell) RE: Introduction to Loops with Java - Ex094 - 08-15-2016 Thanks you guys ![]() (08-14-2016, 08:35 PM)Ao- Wrote: Very well done; good explanations all around. Ruby does ring a bell, I got busy with studies and stuff :S |