COURSES
MBAData Science & AnalyticsDoctorate Software & Tech AI | ML MarketingManagement
Professional Certificate Programme in HR Management and AnalyticsPost Graduate Certificate in Product ManagementExecutive Post Graduate Program in Healthcare ManagementExecutive PG Programme in Human Resource ManagementMBA in International Finance (integrated with ACCA, UK)Global Master Certificate in Integrated Supply Chain ManagementAdvanced General Management ProgramManagement EssentialsLeadership and Management in New Age BusinessProduct Management Online Certificate ProgramStrategic Human Resources Leadership Cornell Certificate ProgramHuman Resources Management Certificate Program for Indian ExecutivesGlobal Professional Certificate in Effective Leadership and ManagementCSM® Certification TrainingCSPO® Certification TrainingLeading SAFe® 5.1 Training (SAFe® Agilist Certification)SAFe® 5.1 POPM CertificationSAFe® 5.1 Scrum Master Certification (SSM)Implementing SAFe® 5.1 with SPC CertificationSAFe® 5 Release Train Engineer (RTE) CertificationPMP® Certification TrainingPRINCE2® Foundation and Practitioner Certification
Law
Job Linked
Bootcamps
Study Abroad
MS in Data AnalyticsMS in Project ManagementMS in Information TechnologyMasters Degree in Data Analytics and VisualizationMasters Degree in Artificial IntelligenceMBS in Entrepreneurship and MarketingMSc in Data AnalyticsMS in Data AnalyticsMS in Computer ScienceMaster of Science in Business AnalyticsMaster of Business Administration MS in Data ScienceMS in Information TechnologyMaster of Business AdministrationMS in Applied Data ScienceMaster of Business Administration | STEMMS in Data AnalyticsM.Sc. Data Science (60 ECTS)Master of Business AdministrationMS in Information Technology and Administrative Management MS in Computer Science Master of Business Administration MBA General Management-90 ECTSMSc International Business ManagementMS Data Science Master of Business Administration MSc Business Intelligence and Data ScienceMS Data Analytics MS in Management Information SystemsMSc International Business and ManagementMS Engineering ManagementMS in Machine Learning EngineeringMS in Engineering ManagementMSc Data EngineeringMSc Artificial Intelligence EngineeringMPS in InformaticsMPS in Applied Machine IntelligenceMS in Project ManagementMPS in AnalyticsMS in Project ManagementMS in Organizational LeadershipMPS in Analytics - NEU CanadaMBA with specializationMPS in Informatics - NEU Canada Master in Business AdministrationMS in Digital Marketing and MediaMSc Sustainable Tourism and Event ManagementMSc in Circular Economy and Sustainable InnovationMSc in Impact Finance and Fintech ManagementMS Computer ScienceMS in Applied StatisticsMaster in Computer Information SystemsMBA in Technology, Innovation and EntrepreneurshipMSc Data Science with Work PlacementMSc Global Business Management with Work Placement MBA with Work PlacementMS in Robotics and Autonomous SystemsMS in Civil EngineeringMS in Internet of ThingsMSc International Logistics and Supply Chain ManagementMBA- Business InformaticsMSc International ManagementMBA in Strategic Data Driven ManagementMSc Digital MarketingMBA Business and MarketingMaster of Business AdministrationMSc in Sustainable Global Supply Chain ManagementMSc Digital Business Analytics MSc in International HospitalityMSc Luxury and Innovation ManagementMaster of Business Administration-International Business ManagementMS in Computer EngineeringMS in Industrial and Systems EngineeringMSc International Business ManagementMaster in ManagementMSc MarketingMSc Business ManagementMSc Global Supply Chain ManagementMS in Information Systems and Technology with Business Intelligence and Analytics ConcentrationMSc Corporate FinanceMSc Data Analytics for BusinessMaster of Business AdministrationMaster of Business AdministrationMaster of Business AdministrationMSc in International FinanceMSc in International Management and Global LeadershipMaster of Business AdministrationBachelor of BusinessMaster of Business Administration 60 ECTSMaster of Business Administration 90 ECTSMaster of Business Administration 90 ECTSBachelor of Business AnalyticsBachelor of Information TechnologyMaster of Business AdministrationMBA Business AnalyticsMSc in Marketing Analytics and Data IntelligenceMS Biotechnology Management and EntrepreneurshipMSc in Luxury and Fashion ManagementMaster of Business Administration (90 ECTS)Bachelor of Business Administration (180 ECTS)B.Sc. Computer Science (180 ECTS) MSc in International Corporate Finance MSc in Sustainable Luxury and Creative IndustriesMSc Digital Marketing
For College Students

Understanding loops-The While Loop in Java

$$/$$

In the previous session, you learnt how to implement conditional statements. Almost all the cases you saw in the previous session took an input and based on the input, checked the conditions, and the program ended.

 

But, what if you need to repeat the same logic for multiple inputs?  Do you write the same logic again and again to check each input? Or would you automate your task using loops to reduce the effort? Let us find how how Java helps us to accomplish this.

$$/$$

Video Transcript

 

Till now you have seen IFL statements in Java and Switch case these both were kinds of conditional statements in Java in which based on a certain condition, one action was executed. Now, those kind of conditional statements were useful in cases in which an action was to be executed exactly once. But there might be certain situations in which you need to perform a repetitive action. That is, you need to keep on performing that action until the user asks to stop it. For example, imagine that you are in a factory and you have a robot. You ask the robot to pick up 100 bricks from the ground and keep them on the wall. So what would you tell the robot to do? Well, you would say that pick up the brick, this will be step one for the robot and then you would ask it to keep it on the wall.

 

So basically, once you give this command, the robot will pick up a single brick from the ground and will place it on the wall. Now, if you want the robot to pick up 100 bricks from the ground and place them on the wall, then you would need to write these two statements hundred number of times in your code. Well, writing these two lines 100 number of times will surely accomplish your purpose but it is a very inefficient way to write a code. The file will become very lengthy and this way of writing these repeated actions one after the other is very unsystematic. So in Java there is an interesting way to do repetitive actions and they can be performed by using loops. In Java, as the name suggests, loops help you to perform a certain action in a loop. That is, you keep on doing these actions until a certain condition is met or while a certain condition is true. Then you keep on doing it. So basically in a robot example, what could be done? Well, you could tell the robot that while you have still not placed hundred bricks till that time keep on picking one brick and placing it on the wall. So the robot will keep on doing this picking and keeping process 100 number of times. So this was one application of using loops in Java. What could be other applications? Now, suppose that your younger brother comes in and he asks you to give you the list of all the even numbers between one to 10. Then what would you do? Will you write print statements for each and every time you encounter an even number? Will you write print two, print four, print six, print eight till you reach print 100? Well, you would have to write these print statements 50 number of times. Wouldn't it be better if you just ask your computer to calculate for each and every number between one to 10 that which number is even and whichever number is even, the computer prints that it would make your life much easier. So basically you can alternatively use loops for that and you can ask the computer to check for all numbers between 1200 and say that if any particular number is even, then print it. Otherwise move on, move on to next number. So this also can be accomplished using loops in Java. So one of the first loops which we are going to take a look at are something which we call as the while loop. So the while loops are useful in those cases wherein you need to perform an action while a certain condition is true, all while a certain condition is not met. So if you had to convert this robot example into a Java code, how would you do that? Well, we could say that as long as the robot has not placed 100 bricks on the wall till that time, the robot needs to pick up one brick and place it on the wall and then increase its own calculation of how many bricks it has placed till now.

 

So basically for converting it into a simple while loop, you would first say that int bricks this bricks variable is going to store the number of bricks which the robot has placed till now. In the beginning of this whole process, the number of bricks placed is zero. So you would initialize the bricks variable from zero. Then you would say you would use the keyword while you say that while the number of bricks is less than hundred, that is the robot has still not placed 100 bricks on the wall. You would say that if bricks that while bricks is less than hundred. What to do? Well, the robot needs to pick up the brick and keep it on the wall and once this is done, we increase the value of the bricks variable. Why do we need to do this? Well, because after these two statements are executed, the robot has successfully picked up one brick and placed it on the wall. So now the value of bricks has incremented from zero to one. So I say that bricks is equal to bricks plus one. So basically what is happening here is that in the beginning my number of bricks placed till now is zero. Then here it checks the condition that while my bricks is less than 100 because my zero is less than 100. So this condition is true. Hence it goes into inside of this while loop and then it executes these three actions. It says pick up the brick, robot picks up the brick, it keeps it on the wall and bricks become incremented by one, that is, from zero the number of bricks will now increase to one. Then in the next step what happens is that again it checks the condition of this while loop, it checks while bricks is less than 100. Now, what are my current number of bricks? My current number of bricks placed till now are one. Now, since one is again less than 100. So this condition is true. So again it's going to go into this while loop. And the robot is going to pick up the brick, it is going to keep it on the wall and the number of bricks are going to increment it by one. So my number of bricks will go on from one till two. Similarly in the next step it will again check while bricks is less than 100. Now my bricks are two. So it will say while two is less than 100. So this condition is true. And again these three steps are going to get executed. So basically these set of actions keep on getting performed till this condition is met. That is till my number of bricks are less than 100. Now what happens in the last step? Imagine that here this process keeps on getting repeated till I reach a point where 100 bricks have been successfully placed. So what's going to happen next? Once my bricks have become equal to 100 then what I do is that I again check the while condition. I say while bricks is less than 100 and bricks is now equal to 100. So basically the condition that 100 less than 100 which is the condition here is false. That is it comes out to be invalid condition. Then what happens is that these three steps will no longer get executed and we are going to come out of the while loop. So once my condition inside the while loop fails to get fulfilled or it becomes a false condition then the while loop automatically breaks and the program comes to an end. So what happens is that using this while loop we have successfully told the robot to keep on picking up one brick and placing it on the wall till it has placed 100 bricks. And as soon as those hundred bricks have been placed this condition no longer holds true. And so the robot stops picking up the brick or keeping it on the wall. So in this way you can use the while loop to perform some repeating action such as this one.

 

Video Recap

 

This segment is about how to use loops in Java. Loops are useful when a repetitive action is needed to be performed. While loops are used in situations where an action needs to be performed while a certain condition is true, and for loops are used when the number of iterations is known. A robot example is used to demonstrate the use of loops, where the robot picks up 100 bricks and places them on the wall. The while loop is used to execute this task by checking if the number of bricks is less than 100. If the condition is true, the robot will pick up one brick and place it on the wall and increment the number of bricks placed. The while loop will continue until the number of bricks placed reaches 100. The segment also explains how loops can be used to print all even numbers between 1 and 10 in Java.

You learned that Java has constructs called loops which can facilitate repeated execution of a certain set of statements until a certain user-defined conditions is met.

 

Let us now see while loops in action through Java code.

 

Note: You can download the following two Java files to practice the codes while watching the video. Right click on the Java files and open them with IntelliJ. Please be careful with the name of each file. The name should be exactly the same as the class name inside it, for the code to run. So make the changes accordingly.

$$/$$

To summarise, here are the important components of any loop:

  1. A starting point.

  2. A loop control variable that’s also called the counter, which keeps track of how many iterations a loop has to run. The counter is incremented after each iteration.

  3. A loop continuation condition which defines how many times a loop has to run. The condition makes sure that the loop runs until an endpoint is reached.

 

$$/$$

In the next segment, you will take a look at some more examples using while loop and will also work on some problems on your own.