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

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Callbacks in JavaScript

Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…

How to create PDF with JavaScript and jsPDF

Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

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…

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