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

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