Introduction to Loops with Java

This tutorial is all about loops, We’ll be taking a look at the types of loops, their syntax, usage and how to implement them. So lets start,

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,

  • FOR Loop
  • WHILE Loop
  • DO..WHILE 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:


for(initialization; condition; increment) {
       //Body
}

  • 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.
for(int i = 0; condition; update) {
    //Body
}
  • 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.
for(int i = 0; i < 2; update) {
    System.out.println("Hello");
}
  • 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.
for(int i = 0; i < 2; i++) {
    System.out.println("Hello");
}

Before we dry run our for loop, The order of execution is:

  1. The Initialization takes place, variable i is created in the memory and assigned the initial value 0.
  2. The condition is checked whether it’s true or false, if the condition is satisfied, the loop will execute the body else it will break execution.
  3. The body of the loop is executed.
  4. The control is sent back to the Update for updating the variable (increment/decrement) after the body has completed it’s execution.

Dry  Run:

Our for loop is:

for(int i = 0; i < 2; i++) {
    System.out.println("Hello");
}
  1. Variable with data type i is created and assigned the value 0
  2. Condition check if the value of i is less than 2, Since i = 0 hence the condition is satisfied
  3. The body executes and print’s “Hello”
  4. The control is sent to the increment and i is incremented by 1, i now has the value 1 (i = 1)
  5. The condition is checked again if i is less than 2, since i = 1 so the condition is satisfied
  6. The body executed and print’s “Hello”
  7. I is incremented by 1 and i now has the value 2 so i = 2
  8. The condition is checked again and since i = 2 so it’s false because our condition is i needs to be less than 2, not equal to 2.
  9. Loop breaks execution

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:

while(condition) {
    //BODY
}

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.

  • Counter Controlled (Control Variable)
  • Flag Controlled (Boolean)
  • Sentinel Controlled (Special value)

Counter Controlled Loop

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.


int counter = 0;
while(counter < 2) {
   System.out.println("Hello");
}

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.

int counter = 0;
while(counter < 2) {
   System.out.println("Hello");
   counter++;
}

Dry Run

Now we shall dry run the counter controlled while loop we just created above,

  1. counter variable with data type int and initial value of 0 is created
  2. While loop starts and checks the condition first if value of counter is less than 2, since it is hence the condition is fulfilled and the body is executed.
  3. First statement of the body is executed and prints “Hello”
  4. The update statement is executed and it increments the control variable by 1 (control = 1)
  5. After the body is executed, the while loop check the condition again and since it’s true again the loop will run.
  6. First statement of the body is executed and prints “Hello”
  7. The update statement is executed and it increments the control variable by 1 (control = 2)
  8. While loop checks the condition, as the counter variable is 2 and the condition is that it must be less than 2, the condition becomes false and the while loop breaks.

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.

boolean flag = true;
while(flag) {
  System.out.println("Hello");
  flag = false;
}

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.

int count = 0;
boolean flag = true;
while(flag) {
  System.out.println("Hello");
  count++;

  if(count == 2) {
     flag = false;
  }
}

Dry Run

  1. Variable with data type int and initial value of 0 is created
  2. Variable with Boolean data type and initial value of true is create
  3. While loop starts and first checks the condition, since flag = true hence condition satisfied and body is executed
  4. “Hello” is printed
  5. count variable is incremented by 1 (count = 1)
  6. If condition is checked, since count = 1 hence the condition is false and the body of the if is not executed. Control is sent back to the loop
  7. While condition is checked, flag = true so as per condition the body is executed
  8. “Hello” is printed
  9. count variable is incremented by 1 (count = 2)
  10. If condition is checked, the condition holds true because count is now 2, body of the if is now executed
  11. Value of flag is changed to false (flag = false), Control is sent back to the while
  12. While condition is checked and since flag is now false, the condition is not valid, loop breaks.

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.

Scanner read = new Scanner(System.in);

String name = "";
while(!name.equals(";")) {
    name = read.next();
    System.out.println("You entered: " + name);
}

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

  1. Scanner object is created with the name read
  2. Variable with data type string and initial value of empty string is assigned
  3. While loop starts and checks if the name is not equal to our sentinel value as our string is empty hence this condition is true and the body of the loop will now execute
  4. Using the scanner object, we read the user input and store it in the name variable
  5. Prints out the contents of the name variable.
  6. While loop checks the condition, it’s again true since user entered a string other than ;
  7. User now inputs character
  8. Prints the content of the name variable.
  9. While loop checks the condition and finds that the name has our sentinel value, loop exits

DO..WHILE Loop

The syntax for the Do While Loop is

do {
  //Body
} while(condition);

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,

int counter = 0;
do {
  System.out.println("Hello");
  counter++;
}
while(counter < 2);

Dry Run

  1. Counter variable with data type int and initial value of 0 is created
  2. The body of do executes
  3. “Hello” is printed
  4. The counter variable is incremented by 1 (counter = 1)
  5. The while loop condition is checked, since counter has the value 1 so the condition is true and the control is sent to do
  6. “Hello” is printed
  7. The variable counter’s value is incremented by 1 (counter = 2)
  8. While checks the condition, as the value of counter is now 2, the condition stands false and the while loop exits.

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s