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!

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *