Methods in Java programming language: Video Lecture 18

This article covers details on methods. It explains why we need to use methods in our programs, how to pass data to a method using parameters, and retrieve information from it via a return statement.

A method is a block of code to perform some specific tasks. One method can be called by another method an arbitrary number of times. That means a programmer can write a method when she or he feels that the lines of codes written in the method will be used multiple times. 

The use of methods can significantly reduce the length of your code. In many computer languages, methods are known as functions because a method is supposed to code some functionality.

The following video lecture explains methods in Java with examples and tracing.

Methods in Java programming language

Structure of a method in Java

Even though we did not explain what methods are in our previous articles, you are already familiar with one method. That method is the “main” method that we have been writing in each of our programs throughout our video lecture series on Java programming.

A method has the following format.

ReturnType MethodName (Parameters){
	// The body of the method
 	——-
	return …
}

The first line of a method is known as the header. A header generally contains a return type, a method name, and some parameters. Then we write the body of the method. The body contains a standard Java code. It may contain return statements too.

A return type

A return type states what kind of information a method will send to its caller. It can be int, double, float, or any primitive data type. It can be even an object or even an array reference. 

Method name

After the return type in the header, we write the method name. The method name cannot be the same as any existing syntax. Also, it has naming rules like — it cannot start with a numerical digit. Uppercase letters are considered different than lower case. It must be one token — which means that there cannot be spaces in the name of the method.

Method parameters

Within parentheses in the header line, we provide parameters. Parameters are inputs to the method. A caller method can send data content to a method using the parameters. We can provide multiple parameters. 

The body of a method

We write the body of a method within curly brackets. The body of the code will contain standard Java codes that we are already familiar with. The body can use the parameters as regular variables. It may create new variables, as well. One can return data to the caller by using a return statement. 

A return statement

Depending on the logic used in the method, the return statement may appear multiple times in the body, but only one of those return statements will execute. Execution of a return statement will take the program to the caller method, from where this method was called. That is, the execution of a return statement ends the execution of the method where it is situated.

The returned data type must match with the ReturnType mentioned in the header of the method.

Which method the Java virtual machine executes first?

The Java virtual machine recognizes the main method and always calls it first. Regardless of where we write our methods, before or after the main method, the Java virtual machine will always start the program from the main method.

A simple method without any parameter and returns

Let us write our first method, that is not the main method. Let us write a method named myGoodMethod before the main method. 

class MethodTest{
  static void myGoodMethod(){
    System.out.println("Hi, my name is Shahriar.");
  }
  
  public static void main(String[] args){
    myGoodMethod();
  }
}

Explaining static 

In the code above, we start the header line of the method myGoodMethod with the syntax static. At this point, it is hard to explain why we are using this syntax static because we have not yet taught the object-oriented paradigm of Java in our Java lecture series. The explanation that does not include the object-oriented concepts is as follows. From a static method, one can only call other static methods. Since our main method is a static one, and we call the newly created method from our main method, we have to make our new method a static one too.

Return type -void

After writing static, we need to write a return type. As said earlier, a return type states what kind of information this method will send to its caller. The method, myGoodMethod, does not return anything. It just prints something. We need to tell Java virtual machine that the method will not return anything. The syntax that states that we will not return anything is void

Method name, myGoodMethod

After writing the syntax “void”, we have to write the method name, which is myGoodMethod. It could be any other name that does not conflict with any existing Java syntax.

No parameter

In parentheses, we provide nothing. Keeping the parameter list empty indicates that the caller can send nothing through the parameter of this method.

The body of the method

In the body of the method, that is within the curly brackets, we write our code. We wrote a System.out.println statement to print, “Hi, my name is Shahriar.”

Calling myGoodMethod from the main method

Now, we can call myGoodMethod from any method. Therefore, we can call myGoodMethod from the main method. To call the method myGoodMethod, we just have to write myGoodMethod in the main method. We also have to provide the necessary parameters in parentheses. In this case, we do not have any parameters. Therefore, we put an empty set of stating and ending parentheses. Then we put a semicolon like any standard java instructions.

The output of the program

Executing the program will print, “Hi, my name is Shahriar.” That means, our main method successfully executed the method named myGoodMethod.

How can we use a parameter in a Java method?

Let us discuss how we can use a parameter. We will change our code a little bit. The goal is to make our method myGoodMethod suitable for printing any name, not just a specific one. We will send the name as a parameter of the method. The method will print the name that it receives.

Here is the modified code.

class MethodTest{
  static void myGoodMethod(String anyName){
    System.out.println("Hi, my name is "+anyName+".");
  }
  
  public static void main(String[] args){
    myGoodMethod("Jane");
    myGoodMethod("John");
    myGoodMethod("Snow White");
  }
}

A parameter in myGoodMethod

When we declare a parameter, we declare it as a variable. We plan to send a name, which is of String type. Therefore, we state that the parameter is of String data type in the parameter part of the header. Then we give the parameter a name. The name of the variable is anyName. Now, the paramter anyName can be used to send a name from the caller method. 

Using the parameter

Whatever content the parameter variable anyName contains, we want the System.out.println method to print that. In place of “Shahriar”, we will print the content of the String variable anyName. In the System.out.println, we write “Hi, my name is”, then we add the variable anyName, and then we add a full-stop symbol.

Now, the method is ready to accept any name from its caller.

Calling with arguments

From the main method, let us call the same method three times, with three different names as the parameter.

In the first call, we provide “Jane” as the argument.

The second call has the argument “John”. 

In the third call, we send “Snow White”.

The instances we pass from the caller are sometimes called arguments. That is Jane, john, and Snow White are three arguments we are passing to the method myGoodMethod via three calls.

The parameter anyName is the variable that captures each of the arguments. 

The output of the program

Once we run this program, we should see three lines starting with “Hi, My name is”, but each line will have a different name, Jane, John, and Snow White. 

Here is the output of the program.

Hi, my name is Jane.
Hi, my name is John.
Hi, my name is Snow White.

Now, we know how to send a parameter. Let us extend this code a bit and learn how to send two arguments in each call.

Sending two arguments in a method

Sending two or more arguments to a method is not that difficult. We can provide parameters separated by commas. 

In our running example, we will use a second paramter to include age of the person whose name is in the first parameter.

Here is the modified class.


class MethodTest1{
  static void myGoodMethod(String anyName, int theAge){
    System.out.println("Hi, my name is "+anyName+". I am  "+theAge);
  }
  
  public static void main(String[] args){
    myGoodMethod("Jane", 20);
    myGoodMethod("John", 19);
    myGoodMethod("Snow White", 23);
  }
}

In this case, let us say that age is an integer. Therefore, we write int then a variable name theAge. We separate the two paramters, anyName and theAge, by a comma.

Now, we can use the variable theAge to pass an integer along with the string anyName.

We change our System.out.println method to the following one, which includes both the variables, anyName and theAge.

System.out.println("Hi, my name is "+anyName+". I am "+theAge);

In the main method, in each of these calls, we have to provide two parameters. The first parameter must be a string, which is inside quotes just like before. There should be a second parameter, which must be an integer because this is how we designed our method named myGoodMethod (String anyName, int theAge).

With each name, we provide a second argument in each call, which is an integer. The call myGoodMethod(“Jane”, 20); indicates that Jane is 20 years old. The next two calls in the main method imply that John is 19 years old, and Snow White is 23 years old. 

Once we execute the program, the corresponding age is printed with each name. Here is the output of the program.

Hi, my name is Jane. I am 20
Hi, my name is John. I am 19
Hi, my name is Snow White. I am 23

Another program with parameters and a return value

So far, we have seen how we can pass arguments to a method. We have not yet seen how we can return something from a method to the caller.

We can use the return statement and the return type to return content to the caller.

Let us work on a different problem now.

The problem and the solution

Let i and j be two integers. i<=j. Compute the summation of all the integers starting from i ending at j.

That is, if i=3 and j=6, then find the summation 3+4+5+6.

For the numbers 3, 4, 5, and 6, the summation will be 18. 

We will write a method that will take i and j as its parameters. The method will return the summation of all integer numbers between i and j. That is, if i is 3 and j is 6, then 18 will be returned by the method. 

Here is the program.

class MethodTest2{
  static int sumitoj(int i, int j){
    int sum=0;
    int a;
    for (a=i; a<=j; a=a+1){
      sum=sum+a;
    }
    return sum;
  }
  
  public static void main(String[] args){
    int s;
    s=sumitoj(3, 6);
    System.out.print("The summation of all integers ");
    System.out.println("between 3 and 6 is "+s);

    s=sumitoj(10, 20);
    System.out.print("The summation of all integers ");
    System.out.println("between 10 and 20 is "+s);
    
    s=sumitoj(1, 100);
    System.out.print("The summation of all integers ");
    System.out.println("between 1 and 100 is "+s);
  }
  
}

Parameters

The name of the method is sumitoj. sumitoj has two parameters, i and j. It returns an integer because the summation of some integers is an integer. The summation can be considered long too but we will keep the return type an integer with an assumption that the summation will not exceed the range on an integer variable. 

Summing the numbers

In the body of the method sumitoj, we declare an integer variable named sum. We will go over every integer between i and j and put the summation in the variable sum.

sum=0 in the beginning.

We write a for loop. We use a loop variable named a. The variable “a” starts from i, goes over every integer, and ends at j.

Inside the loop, we add whatever number we see in the variable “a” with the current sum. Then we remember this summation in the sum variable by assigning the summation to the variable sum (sum=sum+a;). 

Once the execution comes outside the loop, the variable sum contains the summation of all the numbers between i and j.

Return

We then return the value of sum. To do that, we write the following statement.

return sum;

sum is an integer. The return type is also an integer, as we declared. Therefore, the method should work fine.

Calling sumitoj from the main method

We call the method, sumitoj, from the main method three times with parameters

  • 3 and 6,
  • 10 and 20, and
  • 1 to 100.

sumitoj(3, 6) returns 18, as expected. sumitoj(10, 20), and sumitoj(1, 100) return 165 and 5050, respectively. The output of the program reflects the summations. Here is the output of the program.

The summation of all integers between 3 and 6 is 18
The summation of all integers between 10 and 20 is 165
The summation of all integers between 1 and 100 is 5050

The video lecture linked with this article provides a detailed tracing of the program. The video further clarifies how methods execute in a Java program.

Concluding remarks

A programmer generally writes methods for most commonly used functionalities. Instead of writing the same code over and over in the main method, we can call the corresponding method with different arguments.

We will be back with more content soon. To keep in touch, subscribe to our website computing4all.com and to our video channel where we upload our video lectures.

Hope to see you soon in another video. Thank you.

Finding the Largest and the Smallest Numbers in an Array in Java: Video Lecture 17

Finding the largest and smallest numbers in an array is a common programming problem. This post describes how to write a Java program to find the largest or the smallest element in a one-dimensional array. 

In Java Video Lecture 16, we gave two exercise questions on one-dimensional arrays. The exercise questions are as follows.

  • Write a program that starts with an array of ten integers. Print all the numbers on the terminal. Then print the largest number in the array.
  • Write a program that starts with an array of ten integers. Print all the numbers on the terminal. Then print the smallest number in the array.

The Youtube video below explains solutions to the exercise questions mentioned above.

Finding the largest number in an array

Let us assume that we have an integer array, named a, that contains the integers 20, 22, 40, 18, 23, 25, 29, 35, 21, and 17. Let us assume that we will hard-code the numbers as an initialization.

Therefore, we will write the following line.

int[] a={20, 22, 40, 18, 23, 25, 29, 35, 21, 17};

Now, we will write the code to find the largest number in the array a.

Before we write the code to find the largest number, let us write a for loop to print all the numbers on the screen. We use a for loop, with a loop variable named i, to print all the numbers of the array. Here is how we will print all the numbers separated by spaces.

    int i;
    for (i=0; i<a.length; i=i+1){
      System.out.print(a[i]+" ");
    }
    System.out.println();

The line “System.out.println();” is to make sure that there is a new line after printing all the numbers.

Now we will write code to find and print the largest number. The logic behind finding the largest number is the following. 


  •  We will read one number at a time and see if the number we are currently looking at is greater than the largest number we have seen so far.
  • If the number we are looking at is larger than the largest number we have seen so far, then we will remember the number that we are looking at as the largest number.
  • Once we go over all the numbers in the array using this logic, we will find that we have remembered the largest element of the array.

To remember the largest number we have seen so far, we will use a variable. In our code, we will use a variable named largest

Initially, we can just look at the number in the beginning of the array, which is in index 0, and consider that the number in index 0 is the largest number we have seen so far. Therefore, we can declare the variable largest and initialize it to a[0] using the following syntax.

    int largest=a[0];

Then we can go over each of the rest of the indices and check if the content in a later index is larger than what we have in the variable named largest

We will write a loop that will take us to all the indices between 1 and the last index of the array. We need a variable to go over the indices. Let the variable be i. Note that we already copied the content of index zero in the variable largest. Therefore, we do not need to start the loop from zero; rather, we start the loop from 1. 

We will end the loop when the value of the loop variable i becomes equal to the length of the array. That means, as long as i is smaller than the length of the array, we go inside the loop. When i becomes equal to or greater than the length of the array, the loop terminates. In this case, our loop will terminate when i is equal to the length of the array.

Note from Java Video Lecture 16 that the last valid index of the array is one less than the length of the array, a.length. Therefore, the loop termination condition will be i<a.length

The change part of the loop is straight forward because we are going over every index. That means we will increment the loop variable i by one at the end of each iteration (that is, i=i+1). The following lines provide the loop and the logic required to find the largest number in the variable named largest.

    for (i=1; i<a.length; i=i+1){
      if (a[i]>largest){
        largest=a[i];
      }
    }

 When we are inside the loop, a[i] gives us the content in index i of the array. We check if the number in index i, which is a[i], is greater than the number stored in the variable largest using the following if statement: if (a[i]>largest).

Inside the scope of the if statement, a[i] is higher than the number that we remembered in the variable named largest. That means, we have to remember a[i] as our largest number seen so far. Therefore, we copy a[i] to the variable largest using the syntax largest=a[i];

Once the for loop goes over all the elements in the array, we will have the largest number in the variable named largest.

That is, after the for loop ends, the variable named largest contains the largest number of the entire array.

After the execution of the for loop, we can write the content of the variable largest. We use a System.out.println statement, which provides this nice text, “The largest number in the array is: ” then we write the content of the variable largest.

    System.out.println(
            "The largest number in the array is: "+largest);

The complete code, written in a file named LargestNum.java, is provided below.

class LargestNum{
  public static void main(String[] args){
    int[] a={20, 22, 40, 18, 23, 25, 29, 35, 21, 17};
    int i;
    for (i=0; i<a.length; i=i+1){
      System.out.print(a[i]+" ");
    }
    System.out.println();
    int largest=a[0];
    for (i=1; i<a.length; i=i+1){
      if (a[i]>largest){
        largest=a[i];
      }
    }
    System.out.println(
    "The largest number in the array is: "+largest);
  }
}

The output of the program is as follows.

Figure: The output of LargestNum.java.

Finding the smallest number in an array

Finding the smallest number uses the same logic as finding the largest number. Therefore, we will change the previous code instead of starting from scratch.

Printing all the numbers is exactly the same as the previous exercise.

Instead of using a variable named largest, we will use a variable named smallest to remember the smallest number we have seen so far. Here is the core code to find the smallest number.

    int smallest=a[0];
    for (i=1; i<a.length; i=i+1){
      if (a[i]<smallest){
        smallest = a[i];
      }
    }

The content in index zero will be kept in the variable named smallest first. 

In the if statement, previously, we checked if a number stored in index i is greater than the content in the variable largest. Now, we want to check if the content in index i is smaller than the number remembered in the variable smallest. Therefore, we write “if (a[i]<smallest)“.

If we find that the content in index i, which is a[i], is smaller than the smallest number we have remembered so far, we will assign a[i] to the variable named smallest.

 Of course, finally, we will print the variable “smallest”, using the following statement.

    System.out.println(
     "The smallest number in the array is: "+smallest);

Here is the complete code written in a file named SmallestNum.java.

class SmallestNum{
  public static void main(String[] args){
    int[] a={20, 22, 40, 18, 23, 25, 29, 35, 21, 17};
    int i;
    for (i=0;i<a.length;i=i+1){
      System.out.print(a[i]+" ");
    }
    System.out.println();
    int smallest=a[0];
    for (i=1; i<a.length; i=i+1){
      if (a[i]<smallest){
        smallest = a[i];
      }
    }
    System.out.println(
     "The smallest number in the array is: "+smallest);
  }
}

The output of the program is provided below. Notice that the smallest number is printed on the terminal.

Figure: The output of SmallestNum.java.

Additional exercise

  • Find the largest even number in an array. For example, if you have the following array {5, 10, 9, 8, 6, 20, 11, 23}, the program should print 20 because it is the largest even number in the array.
  • Print all the odd numbers in an array. For example, if you have the following array {5, 10, 9, 8, 6, 20, 11, 23}, the program should print 5 9 11 23 because these are the odd numbers in the array.
  • Write a program that will print each other numbers of an array. For example, if an array contains {5, 10, 9, 8, 6, 20, 11}, then the output should be 5 9 6 11.

Concluding remarks

An array is a widely used data structure in any programming language. Practicing with arrays is essential for beginners. Please make sure to practice to improve fluency in the use of arrays in Java. So far, we used integer arrays (int[]), You can practice using other number arrays like double[], float[], long[], and short[].

If you haven’t subscribed to our website Computing4All.com and to this YouTube channel where we host our video lectures, please do so to receive notifications on our new articles and videos.

Please do not hesitate to contact us via the comments section below. 

Happy learning!

Single dimensional array in Java: Video Lecture 16

A single dimensional array or a one-dimensional array can hold more than one element. Using an array, one can avoid the use of too many variables to store the same data types. As an example, a programmer can use an array variable to refer to the GPA scores of many students. In this article, I will discuss how to declare, initialize, and use a single dimensional array.

The items we are going to discuss in this article are as follows:

  1. Why do we need an array variable?
  2. How can we declare an array of a primitive data type?
  3. How can we initialize the array with values? 
  4. Example usage of an array: Sum the numbers stored in an array.

A video to support the discussions of this article is provided below.

Single dimensional array in Java.

Why do we need an array variable?

Suppose that we need to store how many miles each of ten people walked in a month. We will use an integer number for the mileage of each person. In our code, we can write ten variables for ten persons. Such as,

int milep1;
int milep2;
int milep3;
int milep4;
int milep5;
int milep6;
int milep7;
int milep8;
int milep9;
int milep10;

Let us assume that we already know what mileage values should be in the variables. Ten people walked 20, 22, 40, 18, 23, 25, 29, 35, 21, and 17 miles, respectively. Therefore, we can assign the values during the declaration time of the variables.

int milep1=20;
int milep2=22;
int milep3=40;
int milep4=18;
int milep5=23;
int milep6=25;
int milep7=29;
int milep8=35;
int milep9=21;
int milep10=17;

The problem of using too many variables

One problem of using too many variables is that our code cannot be easily generalized. That is, the program will always work only for ten people because it has ten fixed variables to store the monthly mileage of ten people. 

What would happen if we have 20 people? We will need to write another program that has 20 variables. What if we have 1000 people? We will need to write that has one thousand variables to store the walking distance of one thousand people.

Writing variables for so many people is not feasible.

A single dimensional array in Java

We can consider a single dimensional array to be a row of consecutive variables — each cell in the row stores one piece of information, such as the monthly walking mileage of a person. Therefore, instead of creating ten different variables for the walking mileage of ten different people, we will create one array that contains ten cells.

Ten cells of a single dimensional array.

Let us say, the name of the array is “mileage”. The content of the array would be the numbers 20, 22, 40, 18, 23, 25, 29, 35, 21, and 17, that we wan to store for ten people.

We refer each of these cells by a location number. It is intuitive to call these cells the first cell, the second cell, the third cells, so and so forth up to the tenth cell. 

In Java, the first cell has a location number of 0.

The second cell has a location number of 1.

The third cell has a location number of 2.

So and so forth.

Note that the tenth cell of this array has a location number of 9.

Content and indices of the cells of a single dimensional array.

Each location number or a position in an array is called an index. That is, indices start from 0. The last index of the “array” is equal to the “length of the array” minus 1. Therefore, in this array, the last index is 10-1=9.

How can we declare an array of a primitive data type?

One can declare an array of any data type using the following syntax format. 

dataType[] variableName;

In place of the word dataType, we can write whatever primitive data type is appropriate for our program. Some examples of primitive data types are int, double, long, byte, float, and char. In place of variableName, we can write whatever valid name we want to give our variable.

For our running example of walking-mileage, we will use an integer array. Therefore, the declaration will be:

int[] mileage;

Example declarations of some other primitive data types are as follows.

For an array, named mydoublearray, of double-size elements, we use:

double[] mydoublearray;

For an array, named mylongarray, containing long integers, we write:

long[] mylongarray;

That is, we can directly use the element data type and put the start and end square brackets and then provide the array name to declare an array variable.

The difference between a primitive variable and an array variable

An array variable is slightly more complicated than a regular variable. A regular primitive data type variable contains one value only. In contrast, the array variable does not hold one element. Instead, an array variable refers to the starting of several consecutive elements.

If we consider an array a house, the cells are analogous to the rooms of the house. The index refers to a room. The array variable-name refers to the address of the house. 

Similar to the house scenario, the array variable mileage we declared for our running example is an address in the main memory referring to the beginning of our array. That means we still have to create the cells starting from that address. 

Allocating space for the content of the one-dimensional array

To create the actual space to hold a certain number of integers, we have to specifically mention how many cells of integers we want in the array.

The command involves a syntax called new. The following line demonstrates how we can allocate memory for ten cells of integers using the new syntax.

mileage= new int[10];

The syntax new reserves a certain number of cells for a variable. “mileage=new int[10];” will reserve space for 10 integer cells for the array variable mileage.

Instead of writing “int[] mileage;” in one line and then the “mileage=new int[10];” syntax in a second line, we can directly declare and apply the “new” syntax in the same line like the following one.

int[] mileage= new int[10];

Initially, each cell of a newly created array contains a zero as its content. Afterward, we can change the content. 

How to initialize an array

How can we access each cell of the array? Say, we want to put 20, 22, 40, 18, 23, 25, 29, 35, 21, and 17 respectively in the cells of the array mileage

A cell of an array can be accessed by using its index number.

If we want to copy 20 in the first index of the mileage variable, we will write the following code.

mileage[0] = 20;

This command will copy 20 from the right side of the assignment operation, and put it in the index location of 0 of the mileage variable. Similarly, we can put rest of the numbers in the desired locations using more assignments.

mileage[1] = 22;
mileage[2] = 40;
mileage[3] = 18;
mileage[4] = 23;
mileage[5] = 25;
mileage[6] = 29;
mileage[7] = 35;
mileage[8] = 21;
mileage[9] = 17;

The commands have copied content in our entire array. That is, we can access the cells of an array, by writing the index in square brackets after the array name. 

How can we print the elements of an array using a loop?

To print all the numbers in the array, we will go over all the indices. Remember that indices start from 0 and end at “length of the array” minus 1. Therefore, to go over every index, we will need to write a loop that iterates over 0 to the length of the array minus 1.

We can retrieve the length of the array by writing myArray.length, where myArray is the name of the array variable. For our running example, mileage.length retrieves the length of the array.

The following code will print all the numbers in the array on the terminal.

class ArrayExample{
   public static void main(String[] args){
     int[] mileage;
     mileage[0] = 20;
     mileage[1] = 22;
     mileage[2] = 40;
     mileage[3] = 18;
     mileage[4] = 23;
     mileage[5] = 25;
     mileage[6] = 29;
     mileage[7] = 35;
     mileage[8] = 21;
     mileage[9] = 17;
     int i;
     for (i=0;i<=mileage.length-1; i=i+1){
       System.out.print(mileage[i]+" ");
     }
     System.out.println();
   }
 }

In the code above, we have a for-loop. We use an integer variable named i that moves from one index to another. i starts at 0. i is always smaller than or equal to 9 for our array mileage. We write i<=mileage.length-1 in the for-loop. mileage.length is 10 in our running example. Therefore, mileage.length-1 is 9. That is, inside the for-loop, i will vary from 1 to 9.

Of course, we will go to all consecutive indices, so we write i=i+1, in the third part of the for-syntax, indicating that we need the virtual machine to increment the value of i by one at the end of each iteration for the loop.

Inside the loop, all we have to do is to write a System.out.print statement. Within the parentheses, we have to print the content in the ith index of the array mileage. 

That is, we print the content of the cell in index i of the array mileage[i]. We also include a space character after printing mileage[i], so that consecutive numbers are separated when printed.

Outside the loop, we write a “System.out.println();” statement. This statement will ensure that there is a newline after the numbers are printed. That is, the command prompt will appear in another line, not in the same line where the numbers are printed.

After compiling and running the program, we will have all the numbers printed on the terminal.

All the numbers in the array are printed on the terminal.

Direct initialization of an array

We can initialize the array directly during the declaration time. There is a way to initialize during declaration, which implicitly has a new syntax. Instead of writing the initialization lines with ten assignments, we could declare the array variable and initialize it in one line, using the following syntax.

int[] mileage= {20, 22, 40, 18, 23, 25, 29, 35, 21,17};

That is, we can put all the numbers separated by commas within a pair of start and end curly brackets to avoid writing ten additional lines of code. The modified code is the following one.

class ArrayExample{
  public static void main(String[] args){
    int[] mileage = {20, 22, 40, 18, 23, 25, 29, 35, 21, 17};
    int i;
    for (i=0;i<=mileage.length-1; i=i+1){
      System.out.print(mileage[i]+" ");
    }
    System.out.println();
  }
}

The output of the program will remain the same.

Although such direct initialization of arrays is popular in academic settings, in practical programming, there is not much scope to leverage the benefit of direct initialization. In a real-life program, you will ask the user for how many numbers there should be in the array. Then you will use the new syntax to create an array of that size. Then you will ask the user to enter the content of the array. 

Since we are still learning how to use an array, we will keep using such direct initialization for convenience. 

Example usage of an array: Sum all elements

As an example, we will sum up all the elements of the array. Notice that we can use a similar loop to the one that we used to print the elements. 

We will create a variable named sum, which will have zero in it in the beginning. We will go over every element using the index, and add the corresponding content in the array to the sum variable.

The updated program below includes the code for summing up the elements in the previous code.

class ArrayExample{
  public static void main(String[] args){
    int[] mileage = {20, 22, 40, 18, 23, 25, 29, 35, 21, 17};
    int i;
    for (i=0;i<=mileage.length-1; i=i+1){
      System.out.print(mileage[i]+" ");
    }
    System.out.println();
    int sum=0;
    for (i=0;i<=mileage.length-1; i=i+1){
      sum=sum+mileage[i];
    }
    System.out.println("Total mileage: "+sum);
  }
}

The second for loop in the code is for the summation of all the elements. Before the second loop, we declared the integer variable sum. Once we are inside the loop, we deal with the ith index. Our target is to add the content of the ith index of the mileage array to the sum variable.

As an example, when i=5, inside the loop sum should already hold the summation result of all the contents between indices zero to four. 

To add the content of the ith index, with whatever content we have in the sum variable, we write sum+mileage[i]. This is written on the right side of the assignment. The summation result is put back to the variable sum by writing “sum=sum+mileage[i];” inside the loop. 

After the loop ends, we print the value of sum, which contains the summation of all the elements of the array variable mileage.

The program will print total mileage walked by ten people. Here is the screenshot after running the updated program.

The output of the program that sums up all the elements of an array.

The program prints the numbers in the array. Then it prints the summation result.

Exercise

  • Write a program that starts with an array of ten integers. Print all the integers on the terminal. Then print the biggest number in the array.
  • Write a program that starts with an array of ten integers. Print all the integers on the terminal. Then print the smallest number in the array.

Concluding remarks

If you haven’t subscribed to our website Computing4All.com and to the YouTube channel where we host our video lectures, please do so to receive notifications on our new articles and videos.

Please do not hesitate to contact us via the comments section below.

Printing the pyramid pattern of stars in Java: Video Lecture 15

Printing the pyramid pattern of stars is a common practice in learning any programming language. In this post, we will learn how to print the pyramid pattern of stars in Java. The program output for a pyramid of ten lines of stars is provided below.

My Computer$ java Pyramid
Enter number of lines: 10
         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

Video lecture explaining how to print a pyramid of stars in Java

The following video provides a detailed talk on how to print a pyramid pattern of stars in Java.

Printing pyramid patterns of stars in Java

Coming up with the solution

In the video above I discussed how we might draw a Pyramid pattern of stars in Java. I used loops to display the pyramid pattern of stars. I analyzed the problem from a problem-solving viewpoint and then wrote the code. 

Drawing the pyramid pattern is widely used in teaching programming courses because it requires some analysis of the problem before we directly jump into the code.  

Example

    *
   ***
  *****
 *******
*********

Notice in the pyramid above that we have 

1 star in the first line, 

3 stars in the second line, 

5 stars in the third line, 

7 stars in the fourth line, 

And finally, there are 9 stars in the fifth line.

The pattern is such that the number of stars increases in consecutive lines. Our target is to use a loop to go over each line and print the stars. 

Going over lines

In my code, I will use a variable named i, to go over every line of stars. That is, “i” will vary from 1 to 5 for the above example-pyramid contains five lines of stars. 

Finding the relationship between a line and how many stars to print

For such a pattern-printing problem, it becomes beneficial if we can come up with a relationship between a line number i  and how many stars we should print on that line. Let us try to find a connection between the line number and how many stars to print in that line. Let us iterate over the number of stars in the lines again.

When we are in line 1, we print 1 star. 

In line 2, we print 3 stars. 

When we are in line 3, we print 5 stars. 

So and so forth.

The question we are trying to frame here is, when we are in the ith row, how many stars will we print? 

The formula for the number of stars in a line

Notice that the number of stars to be printed = 2*the line number we are currently in minus 1.

That is, if we are in the ith line, the number of stars to be printed is 2*i-1. 

Let us check, if the hypothesis is correct for our running example. 

When we are in the first line, i=1. Therefore, the number of stars in the first line should be 2*i-1=2*1-1=1. Therefore, we print one star in the first line.

When we are in the second line, i=2. Therefore, the number of stars in the second line should be 2*i-1=2*2-1=3. Therefore, we print three stars in the second line.

When we are in the third line, i=3. Therefore, the number of stars in the third line should be 2*i-1=2*3-1=5. Hence, we print five stars.

If we keep doing these calculations, we will see that the formula for the number of stars in the ith line, 2i-1 is correct for any line. 

That is great! We have a formula for the number of stars for the ith line. 

How about the leading spaces

We have left out an important item in our analysis so far. Notice that, printing a pyramid of stars is not just printing stars in a pattern. What do I mean? In each line, we have some spaces before we start to print the stars of that line. The gap becomes smaller and smaller in subsequent lines. In the last line, there is no gap between the border and the first star of that line. These gaps in these lines are actually space-characters. That means we print some spaces before printing the stars in each line.

Let us analyze how many spaces we need to print before printing the stars in each line. That is, using the line number i, we will try to come up with a formula for number spaces in a line. 

Finding the relationship between a line number and number of spaces to print

You can use a paper and draw grids around the stars like the following one. Given that spaces are invisible drawing the grids will help us count the number of spaces in each line. 

A pyramid of stars with grids.

Now, let us count the spaces in each line.

We have 4 spaces in line 1. 

There are 3 spaces in line 2.

We have 2 spaces in line 3

We have 1 space in line 4.

Line 5 contains zero space.

Notice that the number of leading spaces in a line is the total number of lines minus i, where i is the line number.

For example, let us take line 1. Here i=1. The number of spaces is 5-1=4. 

In line 2, i=2. The number of spaces in the second line is 5-2=3.

In line 3, i=3. The number of spaces in the third line is 5-3=2.

In line 4, i=4. The number of spaces in the fourth line is 5-4=1.

In line 5, i=5. The number of spaces in the fifth line is 5-5=0.

The formula for the number of spaces

Notice that for the ith line, if we subtract i from the total number of lines, we will get the number of leading spaces. Therefore, we can say, the number of spaces in line i is equal to n-i, where n refers to the total number of lines.

Summary of the analysis

Based on our analysis, we have come up with two things. 

If we are printing n lines of stars, then

  1. The number of leading spaces in the ith line is n-i.
  2. The number of stars in the ith line is 2*i-1.

We use these two pieces of information in our code.

Pseudocode

Let us write a pseudocode for the solution first. Pseudocode is an informal coding to help design the actual program.

I will ask the user about how many lines the pyramid should contain.

Let us say, the user enters the number of lines in a variable named n.

Then I will write a loop that will iterate n times. To iterate, I will use a variable i. Inside the loop, i contains in which line the program is. Therefore, based on our discussion earlier, we can print n-i spaces first, and then we will print 2*i-1 stars. I will make sure to write a new line after printing al the required stars in a line. Here is the pseudocode.

That’s it. We have the structure of the code. Let us go for coding.

The solution to printing a pyramid pattern

The code below provides a solution to printing a pyramid pattern. The program asks how many lines the pyramid should contain. Then it draws a pyramid containing a total number of lines provided by the user.

import java.util.Scanner;

class Pyramid{
  public static void main(String[] args){
    int n, i;
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter number of lines: ");
    n=scan.nextInt();

    for (i=1; i<=n; i=i+1){
      int sp;
      for (sp=1; sp<=n-i; sp=sp+1){
        System.out.print(" ");
      }
      int st;
      for (st=1; st<=2*i-1; st=st+1){
        System.out.print("*");
      }
      System.out.println();
    }

  }
}

In the pyramid problem, we are given n, the number of lines as the input. We use a Scanner object to get the number from the user.

Then, we write a for-loop to vary the value of variable i, from 1 to n

Now, inside the loop, we will have to print the leading spaces. We write an inner loop to print (n-i) spaces. The loop variable is sp. sp will vary from 1 to (n-i). We will just print a space in each iteration of this inner loop.

After printing the spaces, we have to print the stars. The number of stars we have to print is 2*i-1. We use another loop that iterates 2*i-1 times. The loop variable is st. Inside this loop, we will print a star. 

Finally, after printing the spaces and the stars, we just write System.out.println() without anything inside the parentheses to print a new line. We are done with the code.

Save the file, compile it, and run it. Enjoy the program.

More exercises

Now that we know how to print a pyramid pattern os stars, we can use the knowledge to print other patterns. Write two programs for the following two patterns (Pattern A and Pattern B). The one on the right is slightly harder than the one on the left. Write the code for the left one first and then go for the right one. Enjoy!

Coming up with a program to print Pattern B will be harder than Pattern A.
Both are great exercises to master looping.

Concluding remarks

The purpose of the post is to demonstrate not only to demonstrate how we can print the pyramid pattern but also to demonstrate how to analyze a problem before diving into coding. For most real-life problems, you will see that analysis of the problem and coming up with a sketch of code help write the code quickly. In the given problem, printing the pyramid pattern of stars, I could not write the code without really doing the analysis. I had to figure out how the pattern is changing from one line to another. We need analysis for that.

The summary is, 

  1. Please analyze the problem you are trying to solve before starting to code.
  2. Come up with a sketch of the solution on paper first.
  3. Then go for coding. 

Many times, you will see that coding is the easy part. The analysis is a critical part of programming.

Anyway, if you haven’t subscribed to our website Computing4All.com and to the YouTube channel where we host our video lectures, please do so to receive notifications on our new articles and videos. Please do not hesitate to contact us via the comments section below. See you soon in another post.

Java do-while Loop: Video Lecture 14

Java do-while loop is one of the three looping techniques available with the language. The other two loops are: for loop and while loop. do-while is a little bit different than for or while loops. In the “for” or “while” loop, generally, a condition is checked in the beginning to realize whether the execution should go inside the loop, or not. In contrast, do-while checks for the requirement of iteration at the end of the loop. As a result. do-while would execute the code-block inside the loop at least once.

Java do-while Loop

Java do-while loop has the following structure.

do {
     // Code-block
} while (condition);

The condition is generally an expression that results in either true or false. If the condition results in true, another iteration of the code-block will occur. If the condition becomes false, the loop terminates and executes anything found after the while loop.

Problem Used in the Video

In the video, we demonstrate how to write a program using java do-while loop to repeat the same task based on user preference. The task that the program repeats is the addition of two number provided by the user. The following image provides a screenshot of the program.

A program output that uses Java do-while loop in the code.
Output of a program that uses Java do-while loop in the code.

Notice that the program asks for two numbers from the user. The program prints the summation of the two numbers. Then it gives the user to enter ‘y’ to continue and any other letter to quit the program. The user repeats the task several times by entering ‘y’. When the user enters ‘n’ to quit, the program outputs “Good bye.” and terminates.

We wrote the program using a Java do-while loop. Here is the solution.

The Solution

The solution is provided in the space below.

import java.util.Scanner;

class DoWhileTest{
  public static void main(String[] args){
    double a;
    double b;
    Scanner scan = new Scanner(System.in);
    char decision;
    String str;
    do{
      System.out.print("Enter the first number: ");
      a=scan.nextDouble();
      System.out.print("Enter the second number: ");
      b=scan.nextDouble();
      System.out.println("The addition result is: "+(a+b));
      System.out.print("Enter y to perform more additions.");
      System.out.println("Any other letter to quit.");
      str=scan.next();
      decision = str.charAt(0);
    }while (decision=='y');
    System.out.println("Good bye.");
  }
}

The Video Lecture on Java do-while Loop

The video lecture below explains a lot of details on Java do-while loop.

Video Lecture on Java do-while Loop

Transcription of the Audio of the Video

In this video, we are going to discuss another looping technique known as do-while loops. We will discuss the structure of the do-while loop and compare it with other looping techniques in Java. Definitely, we will write a program to explain how a do-while loop works.

Why do you need a do-while loop?

Hi, I am Dr. Shahriar Hossain. Today, I am going to explain do-while loops in Java. From the previous videos, we are already familiar with for-loops and while-loops. Now the question is, why do we need a third type of loop, named do-while? Its a Good question. A do-while loop is a special kind of looping technique that is suitable for a situation when execution of a code-block is required at least for once.

Now, you may ask if a programmer needs to absolutely know about do-while loops. The answer is, a programmer can avoid do-while loops and use for or while loops with some tricks to do the same work. However, knowing do-while loops makes a programmer’s life easier in some situations.

Moreover, if you have to sit for a programming exam, or go for an interview, you absolutely need to be familiar with do-while loops. Do-while is one of the three looping techniques. As a programmer, we should be familiar with all the three type of loops: for, while, and do-while.

The structure of Java do-while loop and how it compares with other loops

Anyway, let us take a quick look at the structure of a do-while loop.

// Show Handwritten animation

do {
	// code-block
} while (condition);
-----
while (condition){
	// code-block
}
-----
for (initialization; condition; change){
	// code-block
}

The do-while loop starts with the word do. Then the scope of the code-block starts with a curly bracket. At the end of the code block, you end the scope using a closing curly bracket. Then the syntax “while” is written at the end with a condition. We have to put a semicolon at the end of the do-while loop.

Notice that do-while is quite different than while loop and for loop. Do-while is different in the sense that in while and in for loops, the condition is executed before going inside the scope. If the condition results in “true” in a for or while loop, the execution goes inside. If the condition results in false, the condition does not go inside.

In contrast, there is no condition before going inside the code-block of the do-while loop. That means the code-block will execute at least once. At the end, you have the condition with the while. Every time, the code block is executed, the condition-check will evaluate whether another repetition of the code-block is required. If the condition is true, then the code-block will be executed again. Otherwise, the execution will move forward to whatever statements are there outside the do-while loop.

What is a common use of Java do-while loop

A common use of do-while is to check if the user wants to repeat the same work. Let us discuss a program that uses do-while to repeat the same work as long as the user wants it to repeat.

<<Show the terminal output of the program first>>

Consider that we have an amazing program that can add two double-precision numbers. The program asks the user for two numbers. The program then reports the addition result. After the addition, the program asks the user if she/he would like to add more numbers. If the user enters ‘y’ for yes, then the program will ask again for two numbers that the user wants to add.

After the user enters two new numbers, the program will report the new addition result, and ask if the user wants to do more additions. The process will keep repeating as long as the user enters ‘y’. If the user enters ‘n’, then the program will say “Good bye” and terminate.

Starting the code

Let us write code for this program.

At first let us write a program that asks for two numbers, reports the summation result, and then terminates. Later we will modify the code to repeat the task.

Scanner

We already know how to write a Scanner object and ask the user to enter two numbers. We keep the two numbers in two variables named a and b. After receiving the numbers from the user, all we have to do is, to print the summation of the two numbers.

If we compile the java file and run the generated class file, we will notice that the program asks for two numbers from the user, then the program reports the summation, and finally the program terminates.

Java do-while loop

Now, what we want to do is the following – we want to use a do-while loop to repeat this part of the code, where we ask the user for two numbers, and then print the summation result.

Let us write the “do” syntax, and put our code inside the scope of the loop. The loop ends with the syntax “while” and then in parentheses we will need to provide the condition that is responsible for the repeat. Note that we have to put a semicolon at the end of the do-while loop.

Now, we still do not have any information that we can use for the condition that should go here. In fact, with the current code-block, we did not collect any information from the user regarding her or his desire to repeat the addition for another set of numbers.

A character variable

Let us declare a character variable that will help us to store a letter representing user’s desire to repeat. A character variable is able to keep only a letter, digit, or a symbol in it. For example, at can hold, ‘a’, ‘b’, ‘c’, or any letter. A character can hold even a digit like ‘1’ or ‘2’, or ‘3’. It can even hold symbols like ‘+’, ‘-’, or ‘*’. There is a wide range of characters, letters, digits, or symbols that it can hold.

We will ask the user to enter ‘y’ if she or he wants to do another addition. We will ask the user to enter anything else if she or he does not want to do any more addition. We will store whatever the user entered in the character variable named decision, we just created.

Get user-intention regarding repetition

We use the scanner object to get the user input for a character value. Unfortunately, the scanner object does not have a direct method to read a character. We have to read whatever the user enters using a the next() method. We have to keep the information in a String object. str is the String variable. Then we have to retrieve whatever we have in the first position of the String str and put it in the character variable decision. The value zero in the parentheses of charAt gives the first character. Characters in a String starts from 0. That is, the first character of a String has a location of 0, the second character has a location 1, the third character has a location of 2, so and so forth.

Anyway, we just need to take a look at the first character, whether it is ‘y’ or not. If the first character is ‘y’, it will be in location 0 of the String str. Hence, the variable decision will contain ‘y’.

If we find that the variable decision is not ‘, then we do not have repeat anymore.

Now, notice that the repetition of this do-while is dependent on whether the variable decision is ‘y’ or not. Therefore, we can write the condition here as decision ==‘y’. That means, if the decision variable is the character ‘y’, then repeat, otherwise do not repeat.

Single quotes for a character

Note that a character is placed within a single start quote and a single end quote. Without the quotes, the compiler will think that ‘y’ is a variable and will throw and error stating that the variable y is not declared in this program. Therefore, to indicate that we are referring to the exact character value ‘y’, we have to provide the single quotes.

The goodbye message

After the do-while loop terminates, we want the program to write a “Good bye” message. Therefore, we write a System.out.printlin method outside of the do-while loop.

Save, compile, and run

Let us save the file, compile the code,  and execute the generated class file. The user is asked for two numbers. The user enters the two numbers. The program reports the addition result. Then the program asks to enter y, if the user wants to do more additions. The user types ‘y’ and hits the enter button. The program asks for the numbers again. The addition result is displayed. Then the program again asks whether the user wants to do more additions. The user can keep entering ‘y’ here and keep doing additions. When the user enters anything other than ‘y’, the program says “Good bye” and then terminates.

Notice again, how we wrote our program. The code block executes at least once. The decision whether to repeat the code-block or not is made at the end. This structure of do-while is different than for loop and while loop in this way.

Concluding remark

Through this video, we have covered the third looping technique used in Java.  We already learned nested for-loops one of the previous videos. Similar to nested for-loops, you can write nested do-while loops. You can even write one do-while-loop inside a for-loop, or even one for-loop inside a do-while-loop. I hope the concept of looping is clear to you. Please let us know if you have any question through the comment section below. If you haven’t subscribed to our website Computing4All.com and to the YouTube channel where this video is hosted, please do so to receive notifications on our new articles and video lectures.

We wish you become successful in learning to code. Again, please do not hesitate to contact us via the comments section below, if you have any question. Or, even to introduce yourself. See you soon in another video.

Subscribe

Pelase subscribe to receive notifications of new videos and articles.
Subscribe to our YouTube Channel to receive notifications when we post YouTube videos:

While loops in Java: Video Lecture 13

Java has three types of loops: (1) for loop, (2) while loop, and (3) do-while loop. This post focuses on while loops in Java. In the video-lecture associated with this post, we compare side-by-side for loops and while loops.

While loops in Java

The while loop in Java has the following structure.

while (condition){
    //Code block
}

The variable condition must be a result of a boolean expression. That is, the variable condition is a boolean value (true/false). When the variable condition is true, the execution goes inside the code block. After executing the code block, the virtual machine (VM) comes back to the while condition to check if it is still true. If VM finds that the variable condition is still true, the execution goes inside the code block again.

VM keeps repeating the code block as long as the variable condition is true. If in any execution of the code block the value of the variable condition becomes false, then the VM does not go inside the next while-check. Hence the loop stops executing.

Problem Used in the Video

Print all the numbers between 1 and 10, separated by spaces. That is, the terminal output should look like the following one.

1 2 3 4 5 6 7 8 9 10

Of course, we are not going to hardcode ten numbers in a System.out.print statement. We will use a loop to print all the ten numbers. In the video, we will first use a for loop to print the ten numbers. Then, we will modify the for loop to a while loop. The output of the program will remain the same after the changes in the code.

The Solution

The solution using a for loop is provided below.

class WhileTest{
  public static void main(String[] args){
    int i;
    for (i=1;i<=10;i=i+1){
      System.out.print(i+" ");
    }
  }
}

The solution using a while loop is provided below.

class WhileTest{
  public static void main(String[] args){
    int i;
    i=1;
    while(i<=10){
      System.out.print(i+" ");
      i=i+1;
    }
  }
}

The Video Lecture

Here is the video lecture.

While loops in Java.

Transcription of the Audio of the Video

We are going to discuss another looping technique known as While-Loop. Everything we did using Java for-loops in the previous video lectures can be done using while-loops. Watch the video till the end for a detailed explanation on while-loops, a comparison between Java for-loops and while-loops, and a coding-example to explain how while-loops work.

While loop in Java

Hi, I am Dr. Monika Akbar. I am explaining Java while-loops today. A Java while-loop has this structure.

// Hand-draw

while (condition){
       // The code-block under the scope
}

In the while-loop structure, you have a “condition” to control the repetition of the loop. As long as this condition is true, the execution will keep going inside the while-loop and run the code-block again and again.

Inside the code-block, you can write something that will make the condition false after some number of iterations.

For loop in Java

Let us compare the while-loop structure with a for-loop structure. Let us quickly write the for-loop structure.

//Hand-draw

for (initialization; condition; change){      
// The code block under the scope
}

We have initialization, condition, and a change to control the for-loop. In the while-loop, we are missing the initialization, and the change. We have the condition part only. In an ideal looping, along-with the basic while-loop structure, we will need to include initialization and the change part, this way.

Initialization and change in a while loop

// Hand-draw

initialization;
while (condition){
     // The code block under the scope
     change;
}

Let us discuss this using an easy-to-solve example problem. Let us assume that the problem is to print all the numbers between 1 and 10 separated by spaces.

We are starting with a for loop

We can quickly write  a for-loop, in which we use an integer variable i to control the loop. In the initialization, i is equal to 1. The condition is that i  is smaller than or equal to 10. That means, as long as, the variable i remains within the range of 1 to 10, the loop will keep repeating. At the end of each iteration, i will increment by 1, as stated by the third part of the for-syntax.

We print the variable i inside the code. We put a space after i, so that on the terminal a gap is created between the current value of i and the next one.

Please save the file, compile it, and run the generated class file. All the integer numbers from 1 to 10 are printed on the terminal.

To make sure that there is no confusion, this part, containing “My Computer” is my command prompt. The text “My Computer” is not an outcome of the program we have written.

Now, we will use a while-loop instead of the for-loop to do the same task, that is printing the numbers from 1 to 10.

Difference between a for loop and a while loop in Java

Notice that there are some structural differences between a for loop and a while-loop. The basic while-loop only has the “condition” part for which the iteration will go inside. We will include the initialization part outside the while-loop, and the “change” part inside the code-block of while-loop.

Using while loop in Java

Let us keep the line that contains System.out.print  and delete the for structure.

Let us write the while statement. In parentheses we will write the condition for which the System.out.print statement will be executed. If the condition is true, everything inside the curly brackets will be executed.

For the initialization of i, let us write i=1 before the while statement.

After printing the current value of i, we do not want i to retain the same value because we want to print the next number in the next iteration. Therefore, we will change i to the next number. To do that we write i=i+1; right after where the current value of i is printed using the System.out.print statement.

Note that after this code segment executes, a number is printed and the value of i becomes one more than the number that was printed.

This line i=i+1 is responsible for the increment of i. Now, notice that the initialization is i=1. The loop will iterate and at the end of the iteration, the value of i will increase. We need to write a condition within the parentheses of the while-statement. The condition should be such that, the execution goes inside when the value of i is smaller than or equal to 10.

The condition is exactly the same one we had in the for-loop.

The output of the new program

This newly written code is an alternative of the code we wrote using a for-loop. The output of the code should be the same as before.

Let us save the file, compile the code, and execute the generated class file. Notice that we have exactly the same output, where we have all the 10 numbers starting from 1 and ending with 10. The numbers are separated by spaces.

Let us do a side by side comparison of the for-loop and the while-loop. The initialization of the for loop is a part of the structure of the for loop. In the while-loop, we wrote an initialization of the control-variable outside the while loop.

The condition is a part of the for-loop. The condition is a part of the basic while-loop too.

The increment operation is a part of the for-structure. The increment operation was not a part of the basic while-structure. However, we can incorporate the increment, or the change operation inside the code-block of the while loop.

In reality, the for-loop and the while loop can do the same thing.

Concluding remarks

We already learned nested for-loops in the previous video. Similar to nested for-loops, you can write nested while loops. You can even write one while-loop inside a for-loop, or even one for-loop inside a while-loop. The summary is, you can replace a for-loop by a while-loop and vice versa.

I hope the concept of while loop is clear to you. Please let us know if you have any question through the comment section below. If you haven’t subscribed to our website Computing4All.com and to the YouTube channel where this video is hosted, please do so to receive notifications on our new articles and video lectures. We wish you become successful in learning to code. Again, please do not hesitate to contact us via the comments section below, if you have any question. Or, even to introduce yourself. See you soon in another video.

Subscribe

Pelase subscribe to receive notifications of new videos and articles.
Subscribe to our YouTube Channel to receive notifications when we post YouTube videos:

Connected nested loops in Java: Video Lecture 12

As stated in the previous video lecture, nested loops refer to the repetition of another repeated task. The nested loops we discussed in the last lecture were not dependent on each other in determining how many times a loop should iterate. In the exercise of this lecture, we demonstrate how we can ensure that the inner loop iterates a different number of times in each repetition of the outer loop.

We ended the last lecture with an exercise problem. In this lecture, we are going to solve that exercise.

Problem Description of the Exercise

Write a program using nested for loop to print the following pattern of asterisks on the terminal.

**********
*********
********
*******
******
*****
****
***
**
*

The Solution used in the Video Lecture

We wrote the following code in the video to solve the problem described above. Save the program in a file named NestedTri.java.

class NestedTri{
    public static void main(String[] args){
        int i;
        int j;
        for (i=1;i<=10;i=i+1){
            for (j=1;j<=10-(i-1);j=j+1){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

The Video Lecture

The YouTube video lecture is embedded below.

Connected nested loops in Java

Transcription of the Audio of the Video

Hi,
This is Dr. Monika Akbar. I hope that you are enjoying Java programming. In the previous video lecture, we discussed nested loops. We will discuss nested looping in this video too, but there will be some added complexity in it.

You may recall that, we provided an exercise at the end of the previous video. We will solve that exercise here today. Even if you solved the exercise, I suggest that you watch this video because, through the exercise, we will explain nested loops that are connected. The exercise today will demonstrate how the inner loop can be dependent on the outer loop. Here is the exercise problem:

Problem description

Print 10 lines, where the first line, contains 10 asterisks, the 2nd line contains 9 asterisks, the 3rd line contains 8 asterisks, the 4th line contains 7 asterisks, so and so forth. The sample output is provided below.

[Show the sample output.]

**********
*********
********
*******
******
*****
****
***
**
*

[End of sample output]

Again, by watching the video, you will learn nested looping, where the inner loop depends on the outer loop to determine how many times the inner loop should iterate.

Problem analysis

Let us analyze the problem a bit first.

Notice that the output of the problem must contain 10 lines of stars. The first line contains 10 stars. The number of stars reduces by one in the following line. The reduction continues till the tenth line.

Notice that the first line has 10 minus zero asterisks.

Line 2 has 10 minus 1 asterisks.

Line 3 has 10 minus 2 asterisks.

Line 4 has 10 minus 3 asterisks.

So and so forth.

Finally the 10th line has 10 minus 9 asterisks, which is just one star.

If the problem was to print 10 asterisks in each of the 10 lines, we could directly use the technique we learned in the previous lecture. That is, we could write two for loops, where the inner for loop prints 10 asterisks in one line, and the outer for loop repeats the inner for loop 10 times.

Output

Running this code on the terminal will give ten rows, where each row contains 10 asterisks. However, this is not what we want. We need to reduce number of asterisks in the consecutive lines.

[Show the output.]

**********
**********
**********
**********
**********
**********
**********
**********
**********
**********

[End of show the output.]

More analysis of nested loops

Notice that the outer for loop controls which line is going to be printed. That is the variable “i” controls the line number. The inner for loop is responsible for printing certain number of asterisks in a line. Now, We have to change the inner for loop because we are changing the number of stars to be printed for any line. The inner for loop is controlled by the variable “j”.  We will change the inner for loop in such a way that it executes lesser and lesser number of times in subsequent lines.

Recall that, the first line should have all the 10 stars.

The second line should have 10 minus 1 stars, which is 9 stars

The third line should have 10 minus 2 stars, which is 8 stars,

The fourth line should have 10 minus 3 stars, which is 7 stars,

So and so forth.

In the code, in our inner loop, how many stars should be printed is basically controlled by this condition. Currently, the inner for loop is printing 10 stars every time because of this condition.

Now, how can we tell the program that we want to print lesser number of stars than 10, based on – in which line of asterisks – we are currently in. Notice that, the value of the variable “i” holds the information of the current line number. We can use the variable “i” to design how many less number of stars than 10 should be printed.

Controlling the inner loop using the control variable of the outer loop

Recall that, when we are in Line 1, we should print all 10 stars using the inner for loop. Therefore, we want to subtract zero from 10. Since the variable “i” has the value 1 when we are in line 1. We want to subtract i-1 from 10 when the variable “i” is 1. i-1 results in zero because variable “i” is 1.

When we are in Line 2, we want to subtract 1 from 10. In line 2, the value of the variable “i” is 2. Therefore, i-1 is equal to 1. Therefore, by subtracting i-1 from 10, we will be able to print 9 stars.

When we are in Line 3, the value of the variable “i” is 3. Therefore, i-1 will reduce 2 stars from 10, which is 8 stars.

So far, it seems putting 10- (i-1) to control the range of j will work for the first line, the second line, and the third line of asterisks. In fact, it will work for all the following lines.

Output

Let us save the file, compile it, and run the generated class file. We can see that we have the desired output, where the first line contains 10 stars, the second one contains 9 stars, the third one contains 8 stars, so and so forth.

Concluding remarks

The exercise today has shown how we can connect the inner loop with the outer one. There are many other applications that will require such connected nested loops. We will learn them over time with more complex problems.

If you have not yet subscribed to our website Computing4All.com and to this YouTube channel, please do so to confirm that you receive notifications on our new articles and videos. We will see you again in the next video. Wish you a wonderful day, evening, or night, whatever is upcoming. Thank you!

Nested loops in Java: Video Lecture 11

Nested looping refers to a loop inside another loop. Many applications require to loop over a repeated task. Nested looping is a solution to aid such repetitive tasks. As an example, consider printing ten lines on the terminal, where each line contains twenty asterisks, as shown below.

********************
********************
********************
********************
********************
********************
********************
********************
********************
********************

Printing one line of twenty asterisks can be performed using a loop. We can write ten lines of asterisks by running another loop over it ten times.

The Code used in the Video Lecture

In the video, we wrote a code using nested loops that prints the output of ten lines, where each line contains twenty asterisks. The java program is below. Please save the program in a file named Nested.java.


class Nested{
    public static void main(String[] args){
        int i;
        int j;
        for (i=1; i<=10;i=i+1){
            for (j=1;j<=20;j=j+1){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

The Video Lecture

The YouTube Video lecture is embedded below.

Nested loops in Java

Exercise

Write a program using nested for loop to print the following pattern of asterisks on the terminal.

**********
*********
********
*******
******
*****
****
***
**
*

Transcription of the Audio of the Video

Hi,
This is Dr. Shahriar Hossain. How are you today? I hope that you are enjoying Java programming. In this video, I am going to explain nested loops. Nested looping refers to looping over another loop. Many applications rely on multiple levels of nesting. For simplicity, today we will learn how to use one for-loop inside another.

In this video, we will go over one problem. At the end of the video, we will provide an exercise. We will solve the exercise in the next video.

The problem

The problem we are going to solve is as follows: Print 10 lines, where each line contains 20 asterisks. The sample output is provided below.

[Show the sample output.]

********************
********************
********************
********************
********************
********************
********************
********************
********************
********************

[End of — Show the sample output.]

Analyzing the problem

Let us talk about the problem. Print 10 lines, where each line contains 20 asterisks, or stars, or multiplication symbols.

Let us think about the solution. Notice that we need to draw a line of 20 asterisks.

If we can draw one line that has 20 asterisks, we can repeat the process 10 times.

[Show the hand-written code]

Whatever code we will write should have this structure [as shown on screen.] The first thing is, we will try to print one line that contains 20 asterisks. That is, at first, we will solve this subproblem – print 20 asterisks in one line.

Printing one line of asterisks

Let us write our code in the main method in a class named Nested. Obviously, the name of the file is Nested.java.

Printing 20 asterisks can be done by typing writing System.out.println(“********************”);

Hard coding the asterisks will not make your code easy to change. That is, if someone wants to print fifty asterisks in one line, then you have to change the System.out.println with fifty asterisks.

Printing one line of asterisks using a for-loop

Anyway, we are going to use a loop that iterates over a System.out.print statement 20 times.

I am writing the structure of the for loop. As you can see, this for loop is designed to iterate 20 times. The value of the variable j will vary from 1 to 20 in this loop. Inside the for loop I use a System.out.print statement, which prints just one asterisk. Notice that this is a System.out.print statement not a System.out.println statement. That is, each asterisk will be printed one after another one, without any line.

Let us save the file, compile it, and run the generated class file. Twenty asterisks are printed on the terminal. Notice that my command line, which states “My computer” starts right after the last asterisk. I actually want to print all these 20 asterisks in a line. Nothing else should be here.

A new line

What we have to do is, we have to put a new line right after the last asterisk is printed.

Let us put a newline after the for loop ends. That is, after all the asterisks are printed, this System.out.println statement will print a new line. As a result, the text, “My Computer”, which is the prefix of my command prompt will move to the next line. Please notice again, System.out.println without any content in the parentheses simply prints a new line.

Let us save the file, compile it, and run the generated class file. All the 20 asterisks are now printed in one line. We have printed one line of twenty stars. That means we are done with this part. [Show the hand-written pseudocode.] We have to now implement this part, which is repetition of what we have done so far 10 times.

Repeating the previous loop

Now that we have the code to print just one line, we can repeat this part that prints one line of 20 stars, 10 times. If we repeat this part of the code 10 times, we should have the desired output, which is 10 lines, where each line has 20 asterisks.

To repeat this part 10 times, we need another for loop. To control that other for loop, we will need a variable. Let the variable be “i”. We write a for-loop, in which the variable “i” varies between 1 and 10. The code that prints 20 asterisks in a line is inside the outer for loop that iterates 10 times.

Running the program

Now save the java file, compile it, and run the generated class file.

Notice that all the 10 lines are printed. Each line contains 20 asterisks. Therefore, we have solved the problem. [Show the original problem]

Today, we have discussed the nested loops – one loop inside another one.

Nested looping can be more complex than what we have explained so far.

Exercise

We are providing an exercise now.

Print 10 lines, where the first line, contains 10 asterisks, the 2nd line contains 9 asterisks, the 3rd line contains 8 asterisks, the 4th line contains 7 asterisks, so and so forth. The sample output is provided below.

**********
*********
********
*******
******
*****
****
***
**
*

We are giving this problem as an exercise. Please try to solve it before watching the next video.

Concluding remarks

It is fine if you cannot solve it at this point. We generally give exercises that are harder than what we have covered so far. That is what makes learners skilled. We will definitely provide the solution of the exercise and explain some relevant items in the next video.

If you have not yet subscribed to our website Computing4All.com and to this YouTube channel, please do so to confirm that you receive notifications on our new articles and videos. Wish you a wonderful day, evening, or night, whatever is upcoming. Thank you!

An exercise on for-loops and if-else: Video Lecture 10

In the previous video lecture, we learned how to repeat a segment of code using a for-loop. The segment we used for repetition was small. In the following video lecture, we incorporate an if-else structure inside the scope of a for-loop. We use a simple problem to develop this practice scenario.

The Problem used in the Video Lecture

Print all the integer numbers starting between 1 and 20 (including 1 and 20.) Mark each of them by “odd” or “even” based on whether the number is odd, or even. You must use a for-loop in your code to iterate over all the integers in the range.

Sample output is as follows.

1 odd
2 even
3 odd
4 even
5 odd
6 even
7 odd
8 even
9 odd
10 even
11 odd
12 even
13 odd
14 even
15 odd
16 even
17 odd
18 even
19 odd
20 even

The Code used in the Video Lecture

We used the following code in the video lecture. If you decide to use it, please save the code in a file named OddEven.java.

class OddEven{
  public static void main(String[] args){
    int i;
    for (i=1; i<=20; i=i+1){
      if (i%2==0){
        System.out.println(i+" even");
      }else{
        System.out.println(i+" odd");
      }
    }
  }
}

The Video Lecture

The YouTube video lecture is provided below.

Iterating over if-else using a for loop.

Exercise

Print all the numbers between 1 and 25 (including 1 and 25.) Mark the numbers that are divisible by 5 with text “Penta”. A sample output is provided below.

1
2
3
4
5 Penta
6
7
8
9
10 Penta
11
12
13
14
15 Penta
16
17
18
19
20 Penta
21
22
23
24
25 Penta

Transcription of the Audio of the Video

Hi, this is Dr. Shahriar Hossain. I hope that you are enjoying the practice of programming using Java. In the previous video lecture, we learned looping. We now know how to use Java for-loops. Today, we will see how we can put if-else statements within a for-loop.

Let us start with a problem.

The problem

Print all the integer numbers from 1 to 20, and mark each of them by “odd” or “even” based on whether the number is odd, or even.

That is, we need an output like this one, where we have an integer and against every integer we have the information whether the integer is odd of even. We have twenty lines for twenty integers between 1 and 20.

[Show the output]

1          odd
2          even
……
20        even

[End of Show the output]

Components of the program

The program has a few components.

  1. We need to go over every integer number between 1 and 20.
  2. For each of the numbers, we have to check whether the number is odd or even.
  3. Based on whether the number is odd or even, print the number and print the text “odd” or “even”.

Let us write the main method in a class named OddEven. The file name is obviously OddEven.java.

The for-loop

Let us create an integer variable named “i”. This variable “i” will be used to hold all the integer values between 1 and 20. From the previous video lecture, we know how to write a for loop and change the value of a variable. Inside the parentheses of the for loop, we do an initialization. In this case, we want the variable “i” to vary between 1 to 20. Therefore, the initialization for “i” should be 1. We want the value of “i” to become each of the numbers between 1 to 20. Therefore, the condition is that the variable “i” should never be greater than 20. Hence, we write i<=20. As said, the value of the variable “i” should be each number. That is, the value of “i” should  be incremented by 1 after each iteration of the for-loop.

Varying the value of i

Now that we have the structure of the for loop, we can do whatever we want inside the scope of the for loop. This for loop will go inside the scope 20 times. In each of these 20 iterations, the variable “i” will have a value between 1 and 20. Seeing is believing. Let us print the value of “i” inside the scope of the for loop. Let us save the file, compile it, and then run the class file.

Notice that the values of “i” are printed on the terminal. The values are 1, 2, 3, so and so forth, up to 20. Let us get back to the code.

How to find if a number is odd or even

Now, for a value of the variable i, we need to check whether the value is “odd” or “even”. How do we know if a number is odd or even? If you divide a number by 2, if there is a zero remainder, then the number is even. If the remainder is 1, then the number is odd.

For example, if you divide 5 by 2, the remainder is 1. Therefore, 5 is an odd number.

As another example, if you divide 8 by 2, the remainder is 0. Therefore, 8 is an even number.

That is, when you divide an odd number by 2, the remainder is 1. When you divide an even number by 2, the remainder is 0.

When you divide a number by 2, the remainder can be either 0 or 1, nothing else. Therefore, if you divide the value of the variable “i” by 2, and receive a remainder of 0, you can mark the value of “i” as “even”. Otherwise, the value is “odd”.

The remainder operation

In Java, the remainder operation is denoted by the percentage symbol (%). It is commonly called “mod”, which stands for modulus or remainder.

If-else

What we want to say here is the following, if (i%2 ==0) then we want to print the number and print the word “even”.

Otherwise, which is the else part, we want to print the number and the word “odd”.

Equality comparison

Notice that this double equals (“==”)  symbol refers to equality comparison, as explained in one of the earlier videos. We are comparing if the left side and the right side of the “double equals” symbol have the same values. If yes, we execute the scope, otherwise we execute the scope of the else part.

Let us save the file. Compile it and run the class file. Notice that we have printed the numbers and side by the numbers, we have reported whether the number is odd or even.

Concluding remarks

One specialty of this program is that we have incorporated if-else statements inside the for-loop. In the upcoming videos, we will write more complex codes involving looping. In the previous video, I mentioned that there are three types of looping (1) For loops, (2) Wile loops, and (3) Do-while loops. I should mention that the use of “for loop” is sufficient. Still, we will go over while and do-while loops later. For now, I want to let you know that if you know “for loops”, you can practically do whatever things are done with while and do-while loops.

I hope that the videos we are making help you in your quest to learn Java programming. Please write comments below if you have any question. Please subscribe to Computing4All.com and to this YouTube channel if you have not already done so. You will receive notifications on our new posts when you subscribe. Have a  wonderful experience in learning to program. See you soon in the next video.

An introduction to Java for loop: Video Lecture 9

Repetition of segments of codes is an essential part of programming. Repeating the execution of a code segment, a programmer can reduce the size of the code as well as solve problems that require iterations of similar computations for an arbitrary number of times. Java provides three syntaxes for repetition: for loop, while loop, and do-while loop. This article covers Java for loop.

Java for loop

Java for loop is is a powerful syntax to repeat segments of code. It provides integral mechanisms to use variables to control a looping. The “for” syntax itself has three parts: initialization, condition, and change (modification of variables.) These parts are seperated by two semicolons. The basic for-structure is provided below.

for (initialization; condition; change){
// Write the code you need to repeat.
// This is the scope of the for loop.
}

The first part, initialization, is executed only once. It executes before anything else regarding the for-loop has been executed.

The second part, condition, executes each time the execution attempts to go insde the scope of a for-loop. The execution goes inside the loop if the condition results in true, otherwise it terminates the loop.

The third part, change, executes at the end of each iteration. Generally, increment or decrement operations on variables are applied in this part.

All the three parts are optional. Java for loop is a powerful syntax because a programmer can use it quite flexibly and creatively. In fact, knowing just “for loop” from the looping control statments is good enough. A programmer can skip while loop and do-while loop pretty easily, if she/he learns the for-loop well. (If you are reading this page for a coursework, I must tell you NOT TO SKIP while loop and do-while loop.)

The video lecture on Java for loop

The following video provides great details on how to use Java for loops. It is a great introductory material. The last part of the video contains a tracing of the program to visually explain how a Java for loop works.

Java for loop: Problem, solution, and tracing

The code used in the video lecture

Here is the code we used in the video lecture. Save the code in a file named MyCode.java.

class MyCode{
   public static void main(String[] args){
     int i;
     for (i=0; i<5; i=i+1){
       System.out.println("Hello Java!!!");
       System.out.println(i);      
     }
   }
 }

Exercise on Java for loop

Use Java for loop in solving all the problems below.

  1. Write a program to print your name twenty times.
  2. Write a program that sums up all the integers between 1 and 100 (including 1 and 100.) Report the final summation on the terminal.
  3. Write a program that prints all the odd numbers between 0 and 50 on the terminal.

Comment

Please feel free to send us your code in solving the exercises above. Write your questions in the “Comments” section below. We will be happy to help you in problem-solving.

Transcription of the Audio of the Video

Hi, this is Dr. Shahriar Hossain. Have you ever thought about how can we repeat segments of our code for a certain number of times? Like most standard programming languages, Java has three different syntaxes  for repeating a segment of code. These syntaxes are called the “for loop”, the “while loop”, and the “do-while loop.”

Today, we are going to learn the “for loop.”

Sample problem

To explain a sample problem, let us write a program. The problem is to print “Hello Java!!!” five times. Based on topics we have discussed so far in this lecture series, we would write five System.out.println statements to print “Hello Java!!!” five times. If we have to write “Hello Java!!!” one hundred times, we have to write one hundred System.out.println statements. We might even have situations, where we have to repeat the same statement a thousand times. It is not quite practical to repeat statements so many times in the same program. To solve this issue, all languages provide looping.

Java for loop

Java’s “for” control statement has three parts. The first part is initialization. This part is executed once before entering the scope of the for loop. The second part is condition check. As long as this condition check is true, the execution will go inside the scope of the for loop. The third part is something that is automatically executed after each iteration of the scope.

All these three parts are separated by two semicolons, within the parentheses. Now notice that if you initialize a variable in the first part, and increase the variable in the last part, then you can put a condition in the second part to allow the execution to go inside certain number of times. For example, consider that you have a variable named “i”. You initialize the variable “i” to 0. Then you, say in the third part, i=i+1. The third part executes automatically after the execution of the segment scoped by the for loop. Therefore, at the end of each iteration i will automatically be incremented by 1.

You are starting the loop with i=0. After executing the code inside the scope of the for loop, the value of i will become 1 because i=i+1 will execute. In the next iteration, I will remain 1; then at the end of the iteration, i will become 2. This will continue for ever, unless you put a condition in the second part of the three parts of the for loop.

Terminating the loop

You can tell when to terminate the loop. In this example, you can tell “when to stop” based on the value of the variable i. Again, the second part should hold a condition; that is, it should result in a Boolean value. Before executing the scope, the program will check the second part if it is true. If it is not true, then the program will not go inside the loop.

If you type i<5, then it means as long as the value of “i” remains smaller than 5, the execution should go inside the scope of the for loop.

Summary of the three parts

Again, the first part is the initialization and executed only once. The third part is executed after every iteration. The second part is checked for “true” every time the execution attempts to go inside the scope of the for loop.

Since, we have i=0 in the first part, i<5 in the second part, and i=i+1 in the third part, this particular for loop will go inside the scope five times. We will discuss more on this soon in this video.

Let us use a Java for loop in our code

For now, let us change our code with five System.out.println statements so that our code contains only one System.out.println statement, but we repeat that statement five times using a for loop.

I am declaring an integer variable named “i”. I will use this integer variable to control the for loop.

Based on the discussion so far, all we have to do is, write a for loop, in which the first part will contain the initialization. I am putting i=0. In the second part I am putting i<5. In the third part I am writing i=i+1; Notice that, starting from 0, there are five integer numbers that are smaller than 5. Therefore, the loop will execute five times.

Let us save the file, compile, and run it. The program prints “Hello Java!!!” five times.

Values of “i” in each iteration

To check the value of the variable “i” during each of the five iterations, we can write another System.out.println statement, just to print the value of “i”. Save the file, compile, and run it.

Notice that after printing each of the “Hello Java!!!” phrases, we have a number printed in the next line which corresponds to the value of “i” in that particular iteration.

Let us trace the execution of the program.

Tracing the program

I am using a software to trace the program. You are already familiar with manual tracing from the previous video. In this video, I am doing tracing using a software named Netbeans to trace the execution of the code I have written. You do not have to use Netbeans at this point; I am using Netbeans because it gives a good visual illustration of what I am teaching today.

The light green highlight shows where the execution is right now.

I am going to track two items during this tracing. One is the value of the variable “i”  and the other is the Boolean value of “i<5”. I have the output-terminal too.

i=0

Now, the program is in a state where it has created memory space for the variable “i”. The execution is currently in the line where we have the syntax “for”. It has not yet executed the initialization i=0. The first thing the computer will do is execute, the initialization i=0. Then it will check if i<5. Because the variable “i” is zero after the initialization, 0<5 will be true. The execution will go inside the scope of the for loop. Notice that we have two System.out.println statements inside the scope of the for loop. The execution point is now on the first System.out.prinln statement.

At this point, the variable “i” is zero, as you can see here. Also notice that i<5 is true. This is the reason the “for” control statement has allowed the execution to go inside the scope of the for loop. If we execute the current line, which is System.out.println (“Hello Java !!!”), then “Hello Java !!!”  will be printed on the terminal. Our execution point has moved to the next line. Notice that “Hello Java !!!” has been printed on the terminal.

Again, the current value of the variable “i” is 0. Therefore, if we execute the current highlighted line, 0 will be printed on the terminal and here it is. 0 is printed on the terminal.

i=1

After 0 is printed on the terminal, the “for” control statement has executed the scope for the current iteration just once. Now, the third part of the for statement will execute. The third part is i=i+1. Again, the third part is executed at the end of each iteration. Once the variable “i” is incremented by 1, “i” becomes 1 because 0+1 is 1. At this point we are in the second iteration of the scope of the for loop. Notice that i<5 is a true statement because the variable “I” is 1, and 1 is smaller than 5 is a true statement. This is the reason why the execution was able to enter the scope with 1 as the value of i. We print “Hello Java!!!” for the second time on the terminal. Then we print the value of the variable “i”, which is 1 at this point.

i=2

Once the content of the variable “i” is printed on the terminal, i=i+1 will be executed and I will become 2. Since 2<5 is a true statement, the execution will go inside the scope. The first System.out.println will be executed. The execution will now go to the second System.out.println statement. Since the value of “i” is 2, the program will print 2. After printing 2, the third part of the for loop will be executed.

i=3

Therefore, the value of the variable “i” will become 3. Since 3<5 is a true statement, the execution will go inside the scope of the for loop. “Hello Java!!!” will be printed for the fourth time. The value of the variable “i”, which is 3 will be printed.

i=4

The value of the variable “i” will now become 4. Now, 4<5. Therefore, the execution will go inside the scope of the for loop. “Hello Java !!!” will be printed for the fifth time. In the next System.out.println statement 4 will be printed because the variable “i” now contains 4.

Our example loop terminates when i==5

At this point, the third part of the for syntax, which is i=i+1, will be executed. The variable “i” will become 5. Now 5<5 is a false statement. Therefore, the execution will not go inside the for loop anymore. Once the second part of the for loop becomes false, looping is terminated. The execution will jump what we have after the for loop. In our case, it is the closing curly bracket of the main method. Notice that, at this point the variable “i” is 5, and therefore the condition i<5 is false. This is the reason the for loop terminated.

By this time, we have printed “Hello Java!!!” five times on the terminal.

Now, won’t you be able to print “Hello Java!!!” ten times, on the terminal. Or say, print your name on the terminal fifty times, using a for loop? I’m sure you will.

Concluding remarks regarding Java for loops

Now that we can repeat code segments, we can write complicated codes. We can sum up all integers between 0 to 100. Or, we can find if a number is a prime number or not. Note that, you can write arbitrary number of lines inside the scope of the for loop. Those lines may contain anything including if-else if statements, or oven other for loops. More on this in the upcoming videos. If you have not already subscribed to our website Computing4All.com or to this YouTube channel, please do so to receive notifications on our new posts.

Thank you for watching the video. Hope to see you soon in in our video lecture series.