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

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

A Java Approach: Selection Structures - Use Cases

Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

A Java approach: boolean variables

The previous time, we talked extensively about Boolean variables, trying to outline the main operations that can be carried out at a practical level.  Of all the cases examined, we have…

A Java approach: condtional structures

Hello everyone and welcome back! The previous times we have introduced the concept of variable, trying to define some basic concepts about it.  However, some situations suggest that the concept of…

Hashmap: hashing, collisions and first functions

Today we are going to study some concepts closely related to hashmaps. The concepts we are going to see are hashing and collisions. Hashing The idea of hashing with chaining is to…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

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