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

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…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

Top JavaScript libraries and frameworks part 1

JavaScript libraries and frameworks make it easy to develop websites and applications with a wide variety of features and functionality, all with dynamic, flexible and engaging features. According to a 2020…

Looping through a matrix with JavaScript

We were already talking about how to multiply arrays in JavaScript and we realised that we had not explained something as simple as traversing an array with Javascript. So we…

How to multiply matrices in JavaScript

It may seem strange to want to know how to multiply matrices in JavaScript. But we will see some examples where it is useful to know how to perform this…

JavaScript Formatting Date Tips

Something that seems simple as the treatment of dates can become complex if we don't take into account how to treat them when presenting them to the user. That is…

How to make a multilingual website without redirect

Today, we're going to talk about how to implement a simple language selector on the basic static website, without the need of any backend or database calls or redirection to…

Starting with Bootstrap-Vue step by step

Today we will show you how to use BootstrapVue, describe the installation process and show basic functionality. The project’s based on the world's most popular CSS framework - Bootstrap, for building…

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