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 write any kind of program, the notions seen so far might be sufficient. However, a problem arises. How can we perform tasks that require the systematic repetition of a block of code? 


Suppose we have the following exercise: Write a program that prints all natural numbers from 0 to n, where n is given.

We quickly analyse the exercise. We are asked to print a sequence of numbers, starting from 0 and ending with a number, which is given to us (for now, we are not interested in how). We therefore expect an output of type 0, 1, ..., n.

The question I ask now is: with the knowledge acquired so far, are we able to solve this exercise? 

Someone could say yes, and maybe propose a solution like this one: 

public class Main{
    public static void main(String[] args){

The idea of this solution is to assume n known and write as many printing instructions as the numbers 0 to n. There is, however, a big underlying problem. The solutions to the problems must be as general as possible and work with whatever configuration of variables we choose.

If we assume that n from two becomes ten thousand, this code, although syntactically correct, would no longer perform its task, thus becoming useless. We should arm ourselves with patience and write ten thousand printing instructions. An inhuman job, to say the least.

Obviously, this is a trivial example of the need to systematically execute blocks of code. If we can find a mechanism that allows us to repeat a block of instructions, then we have solved our problem and can make much more complex code with much less effort. Fortunately, there is no need to make this great effort at the implementation level, since Java provides us with particular constructs called cycles.

The cycles

After this introduction, we can finally define a cycle. It can be said that:

A cycle is a set of instructions that can be executed repeatedly until a certain condition occurs.

So we immediately understand that, if on the one hand we don't have to make an implementation effort that allows us to create the repetition mechanism, on the other hand the effort to be made concerns two things: the identification of the condition and the identification of the instructions to be repeated.

In the programming, we can basically identify two categories of cycles: 

  • Pre-conditional cycles
  • Postconditional cycles

 First, however, it is good to lay the foundations of a correct vocabulary.

Vocabulary: terminology on cycles

We define guard of the cycle, the condition to be verified to make the cycle continue.

We define iteration as a single repetition of the cycle instructions. 

We define the body of the cycle as the group of instructions that will be repeated.

Pre-conditional cycle

We define a pre-conditional cycle when the condition check is performed before the code execution. The inexperienced student may think that this is not relevant at all. On the contrary, it is of crucial importance. This is because, when I check the condition before executing the code, I may run into the case that the condition is false before the first iteration and therefore not execute the body itself.

Let's see an example, not in Java language, but in natural language.

//program to print numbers from n to 0
n = -1;
until n > 0
    print n
    decreases n

We see that the variable n has been initialized at -1. The cycle guard, however, requires n to be greater than zero. So, at the beginning the guard is already false and therefore the body of the cycle is not executed at all.

Clearly, this is a special case where a logical error is present. It means that we basically "thought wrong". This is not the only case. 

Postconditional cycle

We define a postconditional cycle when the condition check is performed after executing the body of the code. Here too, there are pros and cons. Mainly, we decide to use a post condition cycle when we are absolutely sure that we need to run the body of the cycle at least once. A classic example would be a menu that is displayed until you choose to exit the application.

    show menu
    perform the chosen operation
}as long as different choice from output 

We understand a little better why this is the best choice for this type of problem. It is the best choice because we have the absolute certainty that we want to show the menu at least once. 

The counter cycle

There is this type of cycle which, to tell the truth, cannot be considered a category in itself, as it can always be traced back to one of the previous two. In reality it becomes de facto. It is so used that we can almost define it as a category.

What is the peculiarity. The presence of an entity called a counter. Let's see briefly what it is about.

A counter is basically a variable, whose function is to count

Often, we need to count how many iterations we do. We use this type of concept when, for example, we know a priori that we want to perform the body of the cycle a finite number of times. If we were asked to write a program that prints the entire alphabet in capital letters, we would know a priori that the letters of the alphabet are 26 and that we would have to perform the body of our cycle 26 times. We will see practical examples of these concepts later on.

Insight: the infinite loops

In computer science, an infinite loop is commonly defined as a cycle that never ends. Typically, it is associated with programming errors. In extremely rare cases it is necessary to produce an infinite loop of its own. 

When programming we must always remember that a cycle must always end somehow. A typical example of a loop could be the following.

int n = 0;
until n > 0
    print n
    increases n

We see clearly that this cycle will never end, as we always increase n, moving further and further away from zero. The guard will always be checked and the cycle will never end.

These situations must always be avoided, as they are problems to be managed.

That's all for this time too. I invite you to learn these concepts well, which we will need to write code. I also invite you to become even more familiar with what you have learned so far. 

Try it out, I recommendwink

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 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…

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…

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