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 upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

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…

Clicky