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

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

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

Data structures in Java - Linked Lists

With 2020 we are going to look at a new aspect of programming: data structures. It is often the case that everyone uses structures provided by the various programming languages.…

A Java approach: variables - use case

Hello all friends and welcome back! After the introduction made on the variables, we try to analyse some critical issues that may arise in quite common situations. Let's start by analysing…

A Java approach: variables

Hello everyone and welcome back! Today we will begin a journey that will lead us to study, and possibly review, what are the basics of programming. We will start by talking…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

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