A Java approach: While loop



Hello everyone and welcome back!

After having made a short, but full-bodied, introduction about cycles, today we are finally going to see the first implementations that use what we have called preconditional cycle.

In Java, as in many other programming languages, this type of cycle is translated with the term while, which in Italian can be translated with "until, until when".

Syntax

Let's see, first of all, the syntax of this construct:

while (condition) {
  /*Body of the cycle*/
}

The syntactic definition fully agrees with the theoretical definition. If we reason on the fact that the instructions are executed one after the other, we can immediately understand that the condition for which the cycle continues to iterate is controlled before the execution of the body. From here, we understand that we are dealing with a preconditioned cycle.

Condition of the cycle

It is worth repeating some fundamental concepts regarding the conditions. 

It is good to remember that when you have to do checks, you are dealing with elements of Boolean algebra. Precisely for this reason, the rules that we have defined above apply. 

A fundamental notion to know is that iterations are performed for real. It means that cycles continue to iterate until the condition is true. So, every time we will write a cycle, we will assume that iterations continue to run until the condition is true.

Example 1: Printing numbers from 1 to 10

The first example that it is good to analyze is the case where we want to print the numbers from 0 to 10.

public class Main{
  public static void main(String[] args){
    int i = 0;
    while (i <= 10) {
      System.out.println(i);
      i++;
    }
  }
}

The idea is therefore to declare a variable representing the number to be printed and to initialize it immediately to 0.

After that, you want to print the numbers up to ten, so the condition will be i <= 10. You must then continue to iterate until the variable i has a value less equal to ten. 

The body of the cycle is relatively simple. It is composed of the instruction to print the variable i, and then there is the increment of the variable.

A rather important detail is the fact that also the body of the cycle is contained in a couple of curly brackets. Java allows you to omit these brackets, provided that the body of the cycle is composed of one and only one instruction. Personally, I always avoid doing this even with a view to future code expansion. As long as the code remains as it is, there are no problems. Problems start to arise when it is to be expanded, since errors in the placement of curly brackets are quite common.

Example 2: Printing all even numbers up to a certain limit

Another example that is good to check is the one where we want to print all the even numbers from 0 to a certain limit given from the user.

Let's check the code.

public class Main{
  public static void main(String[] args){
    int i = 0;
    int limit = 100;
    while (i <= limit) {
      if(i%2 == 0){
        System.out.println(i);
      }
      i++;
    }
  }
}

In this case, the complexity of this code increases slightly. In fact, you can see that it is composed of the increment we had before. There is also an if inside it. Implicitly, we understand that the various constructs can be nested inside each other.

The idea behind this exercise is to scroll through all the numbers, and choose from time to time which ones should be printed or not. In this regard it is worth remembering the meaning of the condition within the if. 

Writing i % 2 == 0 means that we are checking that the rest of the division by two of i is zero. Basically, this is the typical check we do to see if a number is even or not. On the contrary, to check if we want to print all odd numbers, we should modify the if as follows:

if(i%2 == 1){
  System.out.println(i);
}

This is because an odd number is nothing more than a number that, when divided by two, returns 1 as the rest.

Example 2: alternative solution

An alternative solution that is much more easier can be the following:

public class Main{
  public static void main(String[] args){
  int i = 0;
  int limit = 100;
    while (i <= limit) {
      System.out.println(i);
      i=i+2;
    }
  }
}

Example 3: printing a rectangle of *

A third example worth seeing involves printing a rectangle, composed entirely of *.

It is not an example that will have a direct utility during daily programming experiences, but it helps us to understand how it is possible to nest two cycles.

As usual, let's see the code now and then comment it.

public class Main{
  public static void main(String[] args){
    int base = 5;
    int height = 4;
    int i = 0;
    int j = 0;
    while(i < height){
      while(j < base){
        System.out.print("*");
        j++;
      }
      i++;
      j = 0;
    }
  }
}

Compared to the two previous examples, this code is apparently much more complicated, but we will see together that this is not the case.

The idea behind it is that we can accomplish this simple task by printing a series of lines composed of asterisks. In particular, the lines will be as long as the base, and the number of lines to print is determined by the height variable.

So, I wrote the most external cycle, having as condition i < height, thanks to which we are able to iterate a number of times equal to height. We need this to print the horizontal lines.

The innermost cycle has as condition j < base, thanks to which we are able to print a horizontal line of asterisks. Then, by combining these two cycles, we can print a composite figure. 

The output pf the program shown before will be the following:

*****

*****

*****

*****

Conclusions

To study the behavior of the while loop I have provided three rather emblematic examples, which show three fundamental characteristics of this construct. 

We saw a basic example, then we analyzed how it is possible to create more complex cycles and finally, with the last example. 

Also for this time that's all. As always, I invite you to experiment and do tests wink

 
 
Alessio Mungelli

Alessio Mungelli

Computer Science student at UniTo (University of Turin), Network specializtion, blogger and writer. I am a kind of expert in Java desktop developement with interests in AI and web developement. Unix lover (but not Windows hater). I am interested in Linux scripting. I am very inquisitive and I love learning new stuffs.

 
 
 

Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration