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

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…

Dates in local format with Javascript

In the articles we have about dates in JavaScript we were missing one about how to create dates in local format with JavaScript. That is to say, being able to…

Formatting hours in Javascript

Continuing with the set of articles that talk about internationalisation elements, like the previous one where we talked about relative dates in JavaScript, we will see in this one how…

Request data with prompt in JavaScript

After having published several articles about how to manipulate arrays and dates, today I will publish a post that some of you will find too basic and others will find…

Relative dates in JavaScript

One of the interesting things about the internationalisation library represented in the Int object is the handling of relative dates in Javascript. This handling allows us to represent a date…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

The JavaScript forEach loop

We have already talked about how to handle some of loops  types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how…

What are React Hooks and what problems they solve

Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

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