Another tutorial on recursion

Recursion in Java: Another beginners’ guide: Video Lecture 20

This post is a continuation of the previous video lecture on Recursion. The current post and the associated video lecture explain more on recursion in Java. We target the following problem — how to compute the summation of all the integer numbers between 1 and n, using recursion.

Recall from the previous post that we can go over a series of numbers using recursion. In the previous lecture, we used recursion to print all the integer numbers between 1 and n. The recursive method had a void return type. That is, the method did not return any value but the execution only. In the current post, the recursive method has an int return type.

The problem description

In the current post and the in the video, we apply a mathematical operation (summation) over a series of integer numbers. The recursive method in the current post has an integer return type. Basically, we are solving an exercise question that I provided in the previous post.

Again, the exercise question we are targeting is — Add all the numbers between 1 and n, of course, using recursion. A condition is: n>0.

We can write the series of integer numbers as:

1+2+3+4+… … … +n

Also, instead of writing 1+2+3+4+ …. +n, we can rewrite the series as

n+ ….. … … +4+ 3+ 2+1

That is, I can write the numbers backward, without changing the content of the series.

We can put some more values, in terms of n, here in the sequence. It is just inclusion of more terms of n in place of some of the dots. The series is the same as before.

n+(n-1)+(n-2)+ ….. … … +4+ 3+ 2+1

Note that, n is the largest number in the series. The next number is one less than n, which is (n-1). The number after that is 2 less than n. Therefore, it is (n-2), so and so forth. The numbers added in the series become smaller and smaller, ending with 4+3+2+1.

We do not add anything smaller than 1 in the series because there is a condition with the problem description that n>0. That means, any number in the series has to be greater than 0 because any number can be considered n since it is the variable to this problem.

The associated video lecture

The following video lecture contains a video-version of this post.

Recursion in Java (The second video lecture on recursion)

Looking at a series as a function

Let us say that the function that sums up all the integer numbers between 1 and n is called adder. adder is a function of n. We write it as the word adder, and then within parenthesis we write (n). That is the function is written as adder(n).

We write:

adder(n)=n+ ……… +4+ 3+ 2+1

Or, adder(n)=n+(n-1)+(n-2)+ ….. … … +4+ 3+ 2+1

An iterative solution

It is easy to write a method to implement the function adder(n) using a loop. Let us write a Java method that implements the iterative adder(n) function.

import java.util.Scanner;
class Summation{
  public static void main(String[] args){
    Scanner myScanner = new Scanner(System.in);
    System.out.print("What is the value of n: ");
    int n=myScanner.nextInt();
    int s=adder(n);
    System.out.println("The summation is: "+s);
  }
  static int adder(int n){
    int sum=0;
    int i;
    for (i=n; i>0 ; i=i-1 ){
      sum=sum+i;
    }
    return sum;
  }
}

Notice that the method adder in the code has a for-loop that helps iterating over all the integer numbers starting from n ending at 1. The loop adds each number to the sum variable during the iterations. The method returns the integer, sum, which holds the summation of all the numbers.

Note from a previous lecture on methods that we have to declare the adder method as a static one, because we are calling adder from the main method, which is a static one.

The output of the iterative solution

Let us save the file, compile it, and run it. Here is the output.

My Computer$ javac Summation.java 
My Computer$ java Summation
What is the value of n: 5
The summation is: 15
My Computer$ java Summation
What is the value of n: 100
The summation is: 5050
My Computer$

Notice that the user enters n equal 5 and the program prints 15, which is the summation 5+4+3+2+1.

The user enters 100 in place of n and the program prints 5050, which is the summation of all the integer numbers between 1 to 100.

The program is working perfectly. However, the problem description states that we should not use a loop, rather we should use recursion to solve this problem.

Therefore, let us change the method adder in such a way that it does not contain any loop.

Looking at a series as a recursive function

We already wrote an iterative method static int adder(int n), as our solution. We need to modify that method to get rid of the loop.

Here is the sequence we want to code:

n+(n-1)+(n-2) ….. … … +4+ 3+ 2+1

As explained before, at first we have n. The next number is one less than n, which is n-1. The number after that is 2 less than n. Therefore, it is n-2, so and so forth. Finally, the numbers added become smaller and smaller, such as, 4, 3, 2, and 1.

Mathematically,

adder(n)= n+(n-1)+(n-2)+ ….. … … +4+ 3+ 2+1

Now, notice that, the part that contains (n-1)+(n-2) ….. … … +4+ 3+ 2+1, can be considered adder(n-1).

Hence, we can write

adder(n)=n + adder(n-1)

adder(n-1) already has every term from n-1 down to 1 in it. Therefore, adding n with adder(n-1) will give adder(n).

As an example, when n=5:

adder(5)=5+4+3+2+1

With n=4, adder(4)=4+3+2+1

Therefore, we can replace the 4+3+2+1 part of the adder(5) equation, by adder(4)

That is, we can rewrite:

adder(5)=5+adder(4)

therefore, the general equation is:

adder(n)=n + adder(n-1)

Notice that the above mathematical definition of adder(n) is already a recursive equation. In the left side, we have the function adder with parameter n. In the right side we have the same function “adder” but with a smaller parameter, (n-1).

The problem description already states that n should be greater than 0. That means, if the recursion ever reaches to a parameter with value 0, we should return something that does not contribute to the summation. Something that does not contribute to a summation is zero. That mean, no harm is done if we add 0 to anything. Therefore, we will return a 0 instead of further going inside another recursion, when the parameter itself is 0. Hence we have a base case, which is returns 0 when n becomes smaller than 1.

Let us code the items we discussed.

The recursive solution to the problem

We need to delete the loop entirely from the method adder of the iterative solution. Let us keep the sum variable. The variable sum now should be n+adder(n-1) based on our discussion above. We are still returning sum, just like when we had a loop. The recursion will do the work of looping.

The recursive solution is as follows. We only made changes to the adder method.

import java.util.Scanner;
class Summation{
  public static void main(String[] args){
    Scanner myScanner = new Scanner(System.in);
    System.out.print("What is the value of n: ");
    int n=myScanner.nextInt();
    int s=adder(n);
    System.out.println("The summation is: "+s);
  }
  static int adder(int n){
    if (n<1){
      return 0;
    }
    int sum=0;
    sum=n + adder(n-1);
    return sum;
  }
}

The following part of the adder method is the base case.

    if (n<1){
      return 0;
    }

The line

sum=n + adder(n-1);

has the recursive call to adder, where (n-1) portion of the problem is solved. That is, one adder method performs one addition only; the rest of the additions are performed in other recursive calls.

The output of the recursive solution

The output of the recursive program is no different than its iterative version. Note that we solved the same problem using iterative and recursive solutions. Therefore, their outputs for the same n will be the same.

Tracing the recursive solution

I highly suggest that you watch the YouTube video above to view how I traced the program for n=3. After watching the video, trace the program with n=4 and n=5, as a practice.

As I said in the earlier lecture, many sophisticated algorithms in artificial intelligence rely on recursion because recursion automatically saves the local variables and the parameters in each call. If you trace the recursive version of the program we have written in the current post, you will see that n has different values in each call.

The reality of a recursive solution

Recursion is an elegant technique. The reality of recursion is that you will prefer an iterative solution over a recursive one if the iterative one is easy to code. Sometimes, recursive solutions are easier to code but can be slower than its iterative version.

The tradeoff between ease of coding and how fast your program runs is a topic that is generally discussed in an Algorithms course. The specific topic is known as algorithm complexity. May be, some day we will discuss about algorithm complexity too.

For now, let us keep practicing and developing our programming skills.

Concluding remarks

If you have not yet subscribed to Computing4All.com and to our YouTube channel, please do so to receive notifications on our new articles and videos. Let us know if you have any questions via comments below.

A simple tutorial on recursion

A beginners’ tutorial on recursion in Java: Video Lecture 19

This article discusses the basics of recursion in Java. We will discuss the theory of recursion, how we can write a recursive method in Java, and how to trace a recursive program.

We are already familiar with how to use methods in Java. A method is a code snippet that you can call an arbitrary number of times from another method. This article explains how we can use a recursive Java method to solve a problem that we could solve using a loop.

In mathematics and computer science, recursion refers to a special technique to solve problems that are difficult to program using loops. The main property of recursion is that a recursive function defines itself, or at least a part of itself. In a recursive method, you will see that the method is calling itself at some point.

Recursion helps solve many complex problems that are difficult to solve using a loop, and at the same time when solving a portion of the problem is easy to tackle. 

Properties of recursion

A recursive method have two properties. 

  1. A base case, or a stopping condition: Of course, we do not want our program to run forever. The recursion — that is the calling of itself — must stop at some point. The condition at which the recursion should stop is called the base case. The base case is generally an easy-to-solve subproblem of the main overarching problem.
  2. A recursive call: In every call, the method must solve a part of the main problem. When the method calls itself, the call must receive a smaller problem than the problem the current method is handling. Structurally, the smaller problem should have the same properties as the current problem. Only the size of the problem should be smaller in the next call. In particular, we have to make sure that each call is moving the granulated subproblem toward the base case, which is the terminating condition.

A video lecture on recursion in Java

The following video lecture complemnts the content of this page. The video lecture explains the theory of recursion, covers the simple examples of this page, and provides a tracing of a recursive function to clarify the concepts.

A video lecture on recursion in Java

A simple problem to explain recursion

Let us say that we have the following problem in hand. 

Write a recursive method that prints all the integer numbers between n and 1. That is, if n=5, we have to print

5 4 3 2 1

If n=3, then we have to print 

3 2 1.

A solution to the problem using a loop

We can easily solve this problem without any recursions. We can directly use a loop. Let us solve the problem with a loop first.

import java.util.Scanner;
class MyPrinter{
  public static void main(String[] args){
    Scanner myScanner = new Scanner(System.in);
    System.out.print("What is the value of n: ");
    int n=myScanner.nextInt();
    int i;
    for (i=n; i>=1; i=i-1){
      System.out.print(i+" ");
    }
    System.out.println();
  }
}

In the program above, we ask the user for the value of n

The loop variable i starts from n and decreases the value by 1 in each iteration. The execution keeps going inside as long as the value of the loop-variable i is greater than or equal to 1. That is, the loop terminates when the value of the loop-variable becomes smaller than 1.

Inside the loop, we have to print the content of the loop variable i, separated by spaces. 

After the loop ends, we write an empty System.out.println statement to make sure that the command prompt appears in the next line instead of in the same line, after the program outputs get printed.

Save the code in a file named MyPrinter.java, compile it using javac, and run it using java.

My Computer$ javac MyPrinter.java
My Computer$ java MyPrinter
What is the value of n: 5
5 4 3 2 1 
My Computer$ java MyPrinter
What is the value of n: 10
10 9 8 7 6 5 4 3 2 1 
My Computer$ java MyPrinter
What is the value of n: 3
3 2 1 
My Computer$ 

The output demonstrates that the program asked for the value of n. The user entered 5. The program printed.

5 4 3 2 1

After running the program again  — the program asked for n, the user entered 10, the program printed all the integer numbers from 10 down to 1.

The output shows another execution of the same program, where the user entered 3 as the valut of n. The program printed

3 2 1

Therefore, the program worked perfectly.

We will solve the same problem, that is printing n integers from n down to 1, using recursion, without using any loop.

A solution to the problem using recursion

We will not use any loop at all. Rather, we will use a recursive method. Let us say that the name of the method is myRecurrence. The method myRecurrence will accept one parameter only, which is n, the number that the user provided. 

Here is the code that uses recursion and no loop.

import java.util.Scanner;
class MyPrinter{
  public static void main(String[] args){
    Scanner myScanner = new Scanner(System.in);
    System.out.print("What is the value of n: ");
    int n=myScanner.nextInt();
    myRecurrence(n);
    System.out.println();
  }
  
  static void myRecurrence(int n){
    if (n<1){
      return;
    }
    System.out.print(n+" ");
    myRecurrence(n-1);    
  }
}

The header of the recursive method, myRecurrence

The return type of myRecurrence is void because it does not need to return anything to the caller. The method has only one parameter. The name of the parameter is n. This parameter n, for the first call from the main method, will hold a copy of the n that the user enters.

Recall from the previous video lecture that the header must start with the word static because we will call the method from the main method, which is a static one.

The base case in myRecurrence

As said earlier, in recursion, there must be two items — a base case and a recursive call. 

A base case is a terminating condition. In this case, our terminating condition is — when n is less than 1. That means, when n is less than 1, we should do nothing but return to the caller because there is nothing else to do. Remember that we have to print up to 1. We do not print anything smaller than 1. 

We write the base case using an if statement. If we find that n is lesser than 1, we say return.

Inside myRecurrence, the base case is written as:

    if (n<1){
      return;
    }

A return statement with an immediate semicolon, in the above base case, indicates a return of execution without any value. Given that the method has a void return type, all we can return is the execution without any content. We have a base case now.

Other recursive properties in myRecurrence

In a recursive method, a part of the whole work will be solved here within the method. The rest of the work, which is smaller in size, will be solve in a different call of the same method.

In this particular body of the method, we solve the problem of printing one number only, which is whatever value came via the parameter n

We simply print n and then put a space. The space is to make sure that there is a gap between the current number printed and the number we will print next. In the method, we wrote:

    System.out.print(n+" ");

Now, the task left is — printing the rest of the numbers. Let us assume we don’t know how to print the rest of the numbers. Again, we have printed n, but we do not know how to print the rest of the numbers, which are n-1, n-2, n-3, so and so forth.

If n is equal to 5, we have printed 5. The rest of the numbers that we need to print are 4, 3, 2, and 1. We do not know how to print them, but we have a method, which is the same method myRecurrence that can print a sequence of numbers down to 1.

What we do is, we call myRecurrence with n-1 as the parameter. That is, if n is 5 in the current method, we are sending 4 as the parameter for the next call.

We write the following line to print all the numbers starting from n-1:

    myRecurrence(n-1);   

Note again – we have a base case. We solve the problem partially within the method. We send the rest of the problem, that is the smaller subproblem to the next call.

The output of the recursive program

Let us save the program, compile it, and execute it.

Like when we used a loop, the program asks for the value of n. The user enters 5. The program prints:

5 4 3 2 1

The same outputs are observed with n=10 and n=3.

Tracing the program

The video above provides a tracing of the code with n=3. It is important to trace a code using pen and paper for two main reasons: (1) tracing slowly helps understand the problem well, and (2) tracing helps in finding logical errors in the code. I suggest that the reader watches the video above to enjoy the tracing of the recursive method we have discussed in this article.

Another recursive problem

As a quick bonus teaser program, let us discuss the solution of another problem, which is relevant to the one that we have discussed above.

Using recursion, write all the integer numbers between 1 and n. That is, if n=5, we have to print

1 2 3 4 5

If n=3, then we have to print 

1 2 3

Notice that in the previous program, we wrote all the number in reverse order. When n was 5 we printed 5 4 3 2 1. Now, we are printing 1 2 3 4 5.

How can we change the previous recursive program to print everything in ascending order?

In the previous problem, we first printed n, and then using another recursion, we printed all the numbers from n-1 down to 1. 

Now, when we go inside the recursive method, we cannot print anything before printing the rest of the numbers. That is, when n is 5, we have to wait till all the other numbers 1, 2, 3,  and 4 are printed.

When n is 4, we have to wait till all the numbers 1, 2, 3, are printed.

When n is 3, we have to wait till all the numbers 1, and 2, are printed.

So and so forth.

We can accomplish by switching these two lines of the previous myRecurrence method.

    System.out.print(n+" ");
    myRecurrence(n-1);   

That is, we can print all the numbers by flipping the above two lines to the following:

    myRecurrence(n-1);   
    System.out.print(n+" ");

The solution

Here is the complete code that prints the numbers in ascending order (1 to n.)

import java.util.Scanner;
class MyPrinter{
  public static void main(String[] args){
    Scanner myScanner = new Scanner(System.in);
    System.out.print("What is the value of n: ");
    int n=myScanner.nextInt();
    myRecurrence(n);
    System.out.println();
  }
  
  static void myRecurrence(int n){
    if (n<1){
      return;
    }
    myRecurrence(n-1);  
    System.out.print(n+" ");  
  }
}

After the base case, in the modified myRecurrence method, we go to recursion without printing n. Numbers smaller than n are processed first. The System.out.print statement will print n, after all the smaller numbers are processed.

If we save this file, compile it, and run the program, we will see that the program is printing all the numbers between 1 to n in ascending order.

My Computer$ javac MyPrinter.java
My Computer$ java MyPrinter
What is the value of n: 5
1 2 3 4 5 
My Computer$ java MyPrinter
What is the value of n: 10
1 2 3 4 5 6 7 8 9 10 
My Computer$ java MyPrinter
What is the value of n: 3
1 2 3 
My Computer$ 

Tracing the program

I suggest that you trace this modified program, to print all numbers in increasing order, using paper and pencil. Again, tracing your code using paper and pencil helps develop an understanding of the logical flow of a program.

When is recursion used?

You might think – why on earth we have solved this simple problem using recursion? The answer is — we have used this simple problem to explain how recursion works. In practice, recursion is used for problems that are hard to code using loops.

There are problems for which it is easier to write a recursive solution than writing a loop-based solution. In games, where it is required to keep track of the status of a game board or in artificial intelligence, where it is required to foresee possible changes, recursion is used because it automatically saves the local variables in each call.

Exercise questions

Question 1: Write a recursive method that takes n as its parameter and then returns 1+2+3+ … … … +n for any n>0.

Question 2: Write a recursive method that takes n as its parameter and then returns the factorial of n for any n>=0. (The factorial of n is referred to as n! and n!=n*(n-1)*(n-2) … … 2*1.) As an example, 5!=5*4*3*2*1=120. Factorial of zero is considered 1. That is 0!=1.

Concluding remarks

If you have not yet subscribed to Computing4All.com or to our YouTube channel, please do so to receive notifications on our new articles and videos. 

Methods in Java programming language

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

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

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 a pyramid pattern of stars in Java

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

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: Coding examples and comparison with for loops

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

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

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!