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? 

Introduction

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){
        System.out.println(0);
        System.out.println(1);
        System.out.println(2);
    }
}

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.

run{
    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

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…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

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…

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