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

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

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

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

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

Printing pyramid patterns of stars in Java

Coming up with the solution

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

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

Example

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

Notice in the pyramid above that we have 

1 star in the first line, 

3 stars in the second line, 

5 stars in the third line, 

7 stars in the fourth line, 

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

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

Going over lines

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

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

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

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

In line 2, we print 3 stars. 

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

So and so forth.

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

The formula for the number of stars in a line

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

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

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

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

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

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

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

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

How about the leading spaces

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

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

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

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

A pyramid of stars with grids.

Now, let us count the spaces in each line.

We have 4 spaces in line 1. 

There are 3 spaces in line 2.

We have 2 spaces in line 3

We have 1 space in line 4.

Line 5 contains zero space.

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

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

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

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

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

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

The formula for the number of spaces

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

Summary of the analysis

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

If we are printing n lines of stars, then

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

We use these two pieces of information in our code.

Pseudocode

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

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

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

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

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

The solution to printing a pyramid pattern

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

import java.util.Scanner;

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

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

  }
}

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

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

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

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

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

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

More exercises

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

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

Concluding remarks

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

The summary is, 

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

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

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

Java do-while Loop: Video Lecture 14

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

Java do-while Loop

Java do-while loop has the following structure.

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

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

Problem Used in the Video

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

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

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

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

The Solution

The solution is provided in the space below.

import java.util.Scanner;

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

The Video Lecture on Java do-while Loop

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

Video Lecture on Java do-while Loop

Transcription of the Audio of the Video

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

Why do you need a do-while loop?

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

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

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

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

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

// Show Handwritten animation

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

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

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

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

What is a common use of Java do-while loop

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

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

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

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

Starting the code

Let us write code for this program.

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

Scanner

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

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

Java do-while loop

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

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

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

A character variable

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

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

Get user-intention regarding repetition

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

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

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

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

Single quotes for a character

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

The goodbye message

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

Save, compile, and run

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

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

Concluding remark

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

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

Subscribe

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

While loops in Java: Video Lecture 13

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

While loops in Java

The while loop in Java has the following structure.

while (condition){
    //Code block
}

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

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

Problem Used in the Video

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

1 2 3 4 5 6 7 8 9 10

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

The Solution

The solution using a for loop is provided below.

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

The solution using a while loop is provided below.

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

The Video Lecture

Here is the video lecture.

While loops in Java.

Transcription of the Audio of the Video

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

While loop in Java

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

// Hand-draw

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

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

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

For loop in Java

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

//Hand-draw

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

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

Initialization and change in a while loop

// Hand-draw

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

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

We are starting with a for loop

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

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

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

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

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

Difference between a for loop and a while loop in Java

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

Using while loop in Java

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

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

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

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

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

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

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

The output of the new program

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

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

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

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

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

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

Concluding remarks

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

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

Subscribe

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

Connected nested loops in Java: Video Lecture 12

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

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

Problem Description of the Exercise

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

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

The Solution used in the Video Lecture

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

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

The Video Lecture

The YouTube video lecture is embedded below.

Connected nested loops in Java

Transcription of the Audio of the Video

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

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

Problem description

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

[Show the sample output.]

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

[End of sample output]

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

Problem analysis

Let us analyze the problem a bit first.

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

Notice that the first line has 10 minus zero asterisks.

Line 2 has 10 minus 1 asterisks.

Line 3 has 10 minus 2 asterisks.

Line 4 has 10 minus 3 asterisks.

So and so forth.

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

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

Output

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

[Show the output.]

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

[End of show the output.]

More analysis of nested loops

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

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

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

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

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

So and so forth.

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

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

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

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

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

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

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

Output

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

Concluding remarks

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

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

Nested loops in Java: Video Lecture 11

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

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

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

The Code used in the Video Lecture

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


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

The Video Lecture

The YouTube Video lecture is embedded below.

Nested loops in Java

Exercise

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

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

Transcription of the Audio of the Video

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

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

The problem

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

[Show the sample output.]

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

[End of — Show the sample output.]

Analyzing the problem

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

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

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

[Show the hand-written code]

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

Printing one line of asterisks

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

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

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

Printing one line of asterisks using a for-loop

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

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

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

A new line

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

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

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

Repeating the previous loop

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

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

Running the program

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

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

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

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

Exercise

We are providing an exercise now.

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

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

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

Concluding remarks

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

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

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

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

The Problem used in the Video Lecture

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

Sample output is as follows.

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

The Code used in the Video Lecture

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

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

The Video Lecture

The YouTube video lecture is provided below.

Iterating over if-else using a for loop.

Exercise

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

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

Transcription of the Audio of the Video

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

Let us start with a problem.

The problem

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

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

[Show the output]

1          odd
2          even
……
20        even

[End of Show the output]

Components of the program

The program has a few components.

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

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

The for-loop

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

Varying the value of i

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

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

How to find if a number is odd or even

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

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

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

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

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

The remainder operation

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

If-else

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

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

Equality comparison

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

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

Concluding remarks

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

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

An introduction to Java for loop: Video Lecture 9

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

Java for loop

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

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

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

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

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

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

The video lecture on Java for loop

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

Java for loop: Problem, solution, and tracing

The code used in the video lecture

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

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

Exercise on Java for loop

Use Java for loop in solving all the problems below.

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

Comment

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

Transcription of the Audio of the Video

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

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

Sample problem

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

Java for loop

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

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

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

Terminating the loop

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

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

Summary of the three parts

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

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

Let us use a Java for loop in our code

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

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

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

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

Values of “i” in each iteration

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

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

Let us trace the execution of the program.

Tracing the program

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

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

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

i=0

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

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

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

i=1

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

i=2

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

i=3

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

i=4

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

Our example loop terminates when i==5

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

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

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

Concluding remarks regarding Java for loops

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

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

An exercise, its solution, and tracing: if-else if-else in Java: Video Lecture 8

In the previous video-lecture, we described how if-else if-else statements work. We provided an exercise with the video-lecture. In the video with this article, we provide a solution to the exercise.

Tracing a program with if-else if-else statements

In the following video, we introduce a technique called tracing that we did not cover before. Tracing is way to analyze a program. Sometimes, the variable space is so large that correctness of the code needs to be checked conceptually. Tracing by hand is a great way to analyze code for correctness.

The video: An exercise and the solution

The video does not only show how I wrote the code to solve a programming problem, but it also shows how I analyzed the problem before starting to code, and how I analyzed the code after writing the code.

Solution using if-else if-else statements in Java.

The if-else if-else exercise (from the previous video post)

Write a program that asks the user for a GPA on a scale of 0.0 to 4.0. If the user enters a number larger than 4.0 or less than 0.0, the program must output “Invalid GPA.” If the user enters a valid number, the program should display the corresponding letter grade based on the table below.

GPA rangeLetter Grade
4.0A+
3.75 to less than 4.0A
3.5 to less than 3.75A-
3.25 to less than 3.5B+
3.0 to less than 3.25B
2.75 to less than 3.0B-
2.0 to less than 2.75C
0 to less than 2.0F

The solution program using if-else if-else statements

We always say that it is better to type your own code because the practice of writing the code connects you with the solution. We are still providing the code below as a reference. If you decide to use the code, please save the code in a file named Exercise.java because the class name is Exercise.

import java.util.Scanner;
class Exercise{
    public static void main(String[] args){
      double gpa;
      Scanner scan = new Scanner (System.in);
      System.out.println("Enter the GPA, please: ");
      gpa= scan.nextDouble();
      
      if (gpa>4.0){
        System.out.println("Invalid GPA.");
      }else if (gpa==4.0){
        System.out.println("A+");
      }else if (gpa>=3.75){
        System.out.println("A");
      }else if (gpa>=3.5){
        System.out.println("A-");
      }else if (gpa>=3.25){
        System.out.println("B+");
      }else if (gpa>=3.0){
        System.out.println("B");
      }else if (gpa>=2.75){
        System.out.println("B-");
      }else if (gpa>=2.0){
        System.out.println("C");
      }else if (gpa>=0.0){
        System.out.println("F");
      }else{
        System.out.println("Invalid GPA.");
      }      
    }
}

Transcription of the Audio of the Video

Hi,

This is Dr. Shahriar Hossain. In the last video lecture, we discussed “if-else if-else” statements. On our website, we provided an exercise. Today, we are going to solve that exercise. If you have already solved the exercise that we provided with the last video lecture, I suggest, please still watch this video till end because it contains some analysis using tracing. Tracing is a technique that helps us analyze our code without running it enormous amount of time with different inputs.

Oh, one thing before we start working on the exercise, please subscribe to our website Computing4All.com and to this YouTube channel to receive notifications about our articles and video lectures.

I will not keep you waiting anymore. Let us work on the exercise.

Problem description

You can see the description of the exercise on the screen now. The exercise states the following: Write a program that asks the user for a GPA on a scale of 0.0 to 4.0. If the user enters a number larger than 4.0 or less than 0.0, the program must output “Invalid GPA.” If the user enters a valid number, the program should display the corresponding letter grade based on the table below.

Then the table provides bunch of ranges for different grades.

We will analyze the problem a bit now.

Problem analysis for if-else if-else statements

At first, I am outlining the range of GPA. Valid GPA may vary between 0 to 4.0. I am drawing the ranges that are mentioned in the description of the exercise. As described in the problem, any GPA greater than 4.0 should be “Invalid.” Also, any GPA smaller than 0 is “Invalid.”

Variable space analysis for if-else if-else statements in a Java program

Now recall, from the table that the letter grade A+ is assigned to GPA 4.0 only.

A GPA in the range from 3.75 to anything less than 4.0 should have a letter grade “A”.

From 3.5 to anything less that 3.75 should be designated as A- (minus).

GPA B+ is in the range starting from 3.25 and should be less than 3.5.

B starts from 3.0. It is less than 3.25.

The range of B- starts from 2.75. B- is less than 3.0.

The next letter grade is C. It starts from 2.0 and is less than 2.75.

Valid grades less than 2.0 result in an F.  

The idea of the solution

The idea of the solution is that we will use if-else if-else statements to display the letter grade corresponding to a given gpa.

Starting of the code

Let us write the code. I have already written the class name and the header for the main method. The file name is Exercise.java.

I will write the code to collect the GPA from the user. I will keep the GPA in a variable named gpa, which is of “double” data type.

Based on what is inside the variable, gpa, I want to display the corresponding letter grade. In our figure, we started to draw the ranges from right side. That is, from larger gpa to smaller gpa. I will write the code in the same order. That is, I will first write an “if” statement to cover the gpa greater than 4.0. Notice that all gpa’s greater than 4.0 should be marked as “Invalid GPA” because the valid gpa range starts at 0.0 and ends at 4.0.

gpa>=4.0

All I have to write is, if gpa is greater than 4.0, then print “Invalid GPA.”

GPA: A+

Now, the next item in the right side of the figure is, 4.0. At 4.0, the letter grade A+ should be printed. The idea is, I will use an “else if” statement to cover 4.0. I am writing else if, gpa is equal to 4.0, then print “A+”. Notice that the equality comparison has to be with two “equals” symbols. We discussed in an earlier video that the equality comparison is always with two equals symbol, not one. A single equals symbol is used for the assignment operations.

Anyway, if we run the program right now, then for any gpa greater than 4.0, the program will print “Invalid GPA”. For gpa equal to 4.0, the program will print “A+”. For any other gpa, the program will print nothing.

We are not going to run the program now. Rather, we will compete the code and then run the program.

GPA: A

The next grade letter is A. GPA A may start at 3.75 and must be less than 4.0. Therefore, I add another else if statement, in which I write the condition gpa>=3.75. When the condition is satisfied, we print the letter grade “A”.

At this point, if we run the program with a gpa, say 3.8, the first condition is not satisfied; the second condition gpa==4.0 is not satisfied either. The third condition gpa is greater than 3.75 is satisfied. Therefore, the program will print the letter grade “A”.

If the first condition is satisfied, which is an invalid situation in this program, the program prints “Invalid GPA” and does not check any other condition in the if-else if sequence. A condition in the if-else if -else sequence is checked only if all the preceding if or else if conditions resulted in “false”. Again, once an “if” or “else if” condition is satisfied, no other condition in the sequence will be checked.

GPA: A-

Let us get back to the code. The next letter grade is A-, which starts from gpa 3.5 and is less than 3.75. Therefore, the condition in the “else if” statement for A- is “gpa>=3.5.”

GPA: B+, B, B-

Let me quickly write the code up to B-, using concepts similar to what we have discussed so far.

GPA: C

Now, notice that the range for C is a bit large. It starts from 2.0 and is less than 2.75. In our code, we provide that condition in the “else if” statement for the letter grade C.

GPA: F

The next letter grade is “F”, which starts at gpa 0.0 and is less than 2.0.

gpa<=0.0

So far, we have all the letter grades in the code. We also have the invalid grade that is greater than 4.0. The only item that is left out is any invalid gpa that is smaller than 0.0. Notice that we do not need another “else if” for that because it is the only situation that is left out. Therefore, we can use “else” without any condition for any gpa lesser than 0.0. We write “Invalid GPA” on the terminal if the user enters any gpa that is negative.

Running the program

The code is complete. Let us save the file and compile it. I will run the program several times with different gpa values. Notice that all the grade letters are correctly printed.

Tracing

Let us manually trace the code a bit for clarity. When you run the program, the Java virtual machine will attempt to execute each line in the main method in a sequence as they appear.

A variable named GPA is created. The Scanner object named “scan” is created. Then, on the terminal “Enter the GPA, please” — this sentence is printed. Then the user enters a GPA and hits the enter button on the keyboard. The computer receives the value of the GPA in the variable named “gpa”. Now the “if-else if” statements of the code will execute, as required. Consider that the user entered a GPA of 3.3.

Tracing with GPA 3.3

Now the computer will check if the variable “gpa” is holding anything greater than 4.0. Since 3.3 is not greater than 4.0, the statement “if gpa>4.0” results in false. Therefore, the corresponding System.out.println “Invalid GPA” will not be executed. Since, “if gpa>4.0” is false, the computer now will check the next “else if” statement, which is gpa==4.0. GPA 3.3 is not equal to 4.0, therefore, the statement “else if (gpa==4.0)” is false. Since, it is false the execution will not go inside its scope. Therefore, “A+” will NOT be printed.

The next item the computer will check if gpa>=3.75. GPA 3.3 is not greater than or equal t 3.75. Therefore, this condition results in false.

The next check is if gpa is greater than or equal to 3.5, which also results in false. Therefore, the computer will check the next “else if” condition, which is if gpa is greater than or equal to 3.25. Now, GPA 3.3 is greater than 3.25. Hence, the condition “gpa>=3.25” results in true. Since it results in true, the execution will go inside the curly brackets, where it is written System.out.println “B+”. Therefore, B+ will be printed. Once one condition is satisfied, that is, once a condition results in true, after executing the corresponding scope, the computer does not check for any other condition.

The execution will jump to the end of this entire “if-else if-else” sequence. That would be the end of the program. That is, for gpa 3.3, the program has printed “B+”.

Tracing with GPA -5.0

Let us quickly trace, another execution of the program, where the user enters -5.0 (negative 5 point 0) as the gpa. Notice that negative 5 point 0 is an invalid GPA because it is less than zero. Let us check how the execution of the program will work now.

We are tracing for the variable gpa, when it is negative 5 point 0. In the first “if” statement, gpa>4.0, the condition is false because -5.0 is not greater than 4.0. Therefore, the corresponding System.out.println is not executed.

For the next “else if” condition, gpa==4.0, the resultant Boolean value is “false” too.

Notice that, for gpa negative 5 point zero, none of these conditions will result in “true”. Therefore, the execution will end up going to the “else” statement. Once, the execution goes to the “else” statement, the computer executes every instruction under the “else” scope. In our code, the only statement written here is System.out.println “Invalid GPA”. Therefore, the computer will execute it and “Invalid GPA” will be printed on the terminal.

Notice again that when, all the “if” and “else if” conditions result in false, only then the last “else” is executed.

Tracing with GPA 3.6

Let us quickly do another tracing for GPA 3.6. gpa>4.0 is false because 3.6>4.0 is false. The next, condition gpa==4.0 is false too. Even the next one, gpa>=3.75 is false. The next “else if” condition gpa>=3.5 is true because 3.6 is greater than 3.5. Therefore, the execution will go inside the scope of “gpa>=3.5”. The computer will execute System.out.println “A-”. No other condition will be checked because already a condition in this sequence of “if – else if” statements is true. The execution will jump to the end of this “if-else if-else” sequence.

Conclusion

I hope the “if-else if- else” statements are clearer with the video lecture today. Please do not hesitate to ask any question you may have via the comments section below. We will be happy to be with you in your journey to learn programming. If you haven’t already done so, please subscribe to our website Computing4All.com and our YouTube channel where you are watching this video.

if-else if-else statements in Java: Video Lecture 7

There are several control statements in Java, among which if-else if-else and switch statements are used for selection operations. The video lecture below explains if-else if-else statements. Programmers use if-else if-else statements for decision making in the code. That is, if-else if-else statements help in executing a part of the code based on certain conditions.

Prerequisites

Please make sure to go over the previous lecture on Boolean Variables and Relational Operators, if you haven’t already done so. The last lecture will give a good idea on Conditions, which is the basis for the current video.

The Video: if-else if-else statements in Java

The video explains if-else if-else statements in Java. It uses a simple example to explain the concept. Overall, the video will help beginners to start practicing if-else if-else statements.

if/else if/else statements in Java

The Program Used in the Video

The program demonstrated in the video is provided below. Please save the code in a file named ConditionTest.java if you want to use the code directly. We suggest that you type the code while you watch the video. When you type the code, you practically develope an understanding regarding the syntax you type.

import java.util.Scanner;
class ConditionTest{
    public static void main(String[] args){
        int x;
        int y;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the 1st number");
        x=scan.nextInt();
        System.out.println("Enter the 2nd number");
        y=scan.nextInt();        
        if (x>y){
            System.out.println("x is greater");
        }else if (x<y){
            System.out.println("x is smaller");
        }else{
            System.out.println("Equal numbers");
        }
    }
}

Exercise to practice if-else if-else statements

Write a program that asks the user for a GPA on a scale of 0.0 to 4.0. If the user enters a number larger than 4.0 or less than 0.0, the program must output “Invalid GPA.” If the user enters a valid number, the program should display the corresponding letter grade based on the table below.

GPA rangeLetter Grade
4.0A+
3.75 to less than 4.0A
3.5 to less than 3.75A-
3.25 to less than 3.5B+
3.0 to less than 3.25B
2.75 to less than 3.0B-
2.0 to less than 2.75C
0 to less than 2.0F

Please do not hesitate to send us your code via the comments section below. We will be happy to provide you feedback.

Comment

Please subscribe to Computing4All.com and to our YouTube channel to stay in touch.

Transcription of the Audio of the Video

From the previous video, you are familiar with comparisons and Boolean variables, we are now moving to what we can do with the comparisons. Practically, we can use comparisons for decision making in the program. That is, a part of our code will be executed if certain conditions are met; otherwise, another part of the code will be executed.

Starting of the code

I am starting my code where I will show how we can use if-else statements. The name of the class is ConditionTest; Of course the file name is ConditionTest.java. I have already written the main method, inside which I will write my code.

I am declaring two integer variables, x and y.

the variable scan is my Scanner object, using which I will get input from the user. I have written my code to get input for the first number x, and the second number y.

The first if statement

At this point, what I will do is, I will print a message if x and y have a certain relationship. The statement is written using “if” then in parentheses state the comparison. Within the parentheses, you must have a Boolean value. Notice that the comparison x>y results in a boolean value, either true or false.

Again, at first write if, then within parentheses provide the condition or comparison that results in a Boolean value. After the parentheses provide the scope of the code that should be executed if the condition in the parentheses results in “true”. You define the scope using a left curly bracket and a right curly bracket.

Anything you write inside the curly brackets will be executed, only if the condition you have provided within the “if” statement results in true. Inside the scope of the if statement I have written, I am writing a System.out.println statement. If x is greater than y, then the System.out.println will print “x is greater than y.”

Save, compile, and run

Let us save the file, compile it and run it. If the user enters a larger number for x than y, then the program should print “x is greater than y”, otherwise the program will print nothing after the user enters the numbers.

The user enters 10 for x and 5 for y. The program immediately prints “x is greater” because the first number the user provided is greater than the second number.

Let us run the code again. The user now provides 10 as the first number and 20 as the second number. Now, the program compares x>y, which results in the comparison 10>20, which in turn results in false. Since the if statement results in false, the System.out.println is not executed. The program just ends without printing anything.

Change the code to include another scope

Now, if we want the program to print something when x is not greater than y, then we can create another scope, which will be executed if the if statement results in false. What we write is, “else” and then we create another scope using left and right curly brackets.  You can print anything inside these curly brackets. Anything you print via a System.out.println statement will be printed on the terminal when x is NOT greater than y. Let us just print “x is not greater.”

Save, compile, and run the code

Let us save the file, compile it, and then run it.

Now, notice that for the first number 10, and the second number 20, the program outputs ” x is not greater.”

Earlier, the program was not printing anything for 10 and 20.

Running the program again with 20 and 10. Now the program is saying “x is greater.” That is if the first number if greater than the second number, the program says “x is greater”, otherwise the program says “x is not greater.”

What happens if you have two equal numbers

Now, what will happen if the user provides two equal numbers, say 10 and 10? Based on the code we have, the program will say that x is not greater. Notice that in the code, the if statement will result in false because x is not greater than y. Therefore, the first System.out.println will not be executed. The execution will go to the else part and execute the System.out.println of the scope of the else, which is “x is not greater.”

What if we want to say something different when x and y have the same value? Practically, we have to include a scope which will be executed when x is equal to y.

In the code, currently, we have if x is greater than y, then do something, otherwise, do another thing. The otherwise part executes only when x is smaller than or equal to y.

We will separate the smaller than part and the equal part. In the else part, we will include another if statement, with a condition x is smaller than y. When x is smaller than y, we want the program to print “x is smaller”.

Save this code, compile, and run the program. When the user puts 10 as the first number and 20 as the second number, the program outputs, “x is smaller.” It is the correct outcome.

When the user enters 20 as the first number and 10 is the second number, the program prints “x is greater.” This is a correct outcome too.

Now notice that when the user enters 10 as the first number and 10 as the second number, the program does not print anything. That is, when the user provides two equal numbers, the program does not go to any of the if scopes.

“The equal to” situation

We would like to see output for “the equal” situation too.

Notice that the first if statement handles the situation with x is greater than y. The second if statement, that is with else,handles the “x is smaller than y” situation. The only situation left is the “x is equal to y” situation. Therefore, we can simply add an “else” to handle the scope of “x is equal to y.” Inside the scope of “else”, we write “equal numbers,” within System.out.println.

We have now written a program that takes two numbers, x and y, from the user and gives an idea of which number is larger, or smaller, or if they are equal.

Let us save the file, compile the code, and run the program. Notice that for equal numbers, the program now outputs “Equal numbers.”

The general structure of if-else if-else statements

[Show the following on screen]

        if (condition 1) {
            ------------
        } else if (condition 2) {
            ------------
        } else if (condition 3) {
            ------------
        } 
            ------------
            ------------
        } else if (condition n) {
            ------------
        } else {
            ------------
        }

[End of — Show the following on screen]

Here is the general structure of “if then else” statements. The first “if” statement is straightforward. If more “if” statements are required in a sequence, they must be preceded by an “else”. You can write as many else if conditions as you need. You may end the if-then-else sequence with just an “else”. The last “else” will cover all situations that are not covered by all the if and else if statements you have in the sequence.

This overall sequence is called if-then-else statements. One thing I should mention is that, each scope under an “if” statement or an “else if” statement or an “else” statement may have many lines of code depending the problem the programmer is trying to solve. In our example, we just had a System.out.println statement within each scope.

Once a condition of the sequence is satisfied, the corresponding scope is executed. Nothing else will execute. The purpose of if-then-else sequence is to execute only one scope.

Conclusion

Please practice what we have discussed today. For exercises, please visit the link provided in the description. Subscribe to this YouTube channel and to our website Computing4All.com. We do not assume that you know anything about programming. Our video lectures, so far, are prepared for beginners regardless of background. Please start from the beginning of this lecture series if you are entirely a new learner.

Thank you very much for watching the video.

Boolean Variables and Relational Operators in Java: Video Lecture 6

A boolean variable is capable of holding either “true” or “false.” A computer program may use one bit only to store the status “true” or “false.” You might already know that the smallest memory unit of the computer is a “bit.” Therefore, a boolean variable uses as little memory as possible to store the information “true” or “false.” Generally, “true” is stored as “1.” “False” is stored as zero (“0”). Anyway, in programming, there are situations when you will want your program to remember some binary decisions (yes/no decisions.) At that time, binary variables become handy. The conclusion whether a number is greater than another number, or smaller than another number, so and so forth can be stored in a boolean variable.

Comparisons between numbers or variables are frequent in programming. That is, you will face situations where you will need to check if one number is smaller than another number, or if a number is equal to or not equal to another number, so and so forth. In mathematics, such comparisons are called logical conditions. In Java, there are six logical operators to work with logical conditions or to compare variables. The video lecture below provides further details with easy-to-follow programming examples.

The Video: Boolean Variables and Relational Operators in Java

The video explains boolean variables and logical conditions (relational operators). The examples we used in the video are suitable for beginners. Overall, the video will help a beginner to study boolean variables as well as relations operators.

Boolean variables and relational operators in Java.

The Program Used in the Video

We wrote the following program in the video. Please save the content in a file named BoolTest.java before compiling and running it. Although we are providing the code here as a reference, we suggest that you type the program yourself while watching the video. The process of programming involves typing and thinking about the problem simultaneously. This is why it is best if you write the code yourself.

import java.util.Scanner;
class BoolTest{
    public static void main(String[] args){
        boolean b;
        int x;
        int y;
        Scanner scan = new Scanner (System.in);
        System.out.println("Enter the 1st number");
        x=scan.nextInt();
        System.out.println("Enter the 2nd number");
        y=scan.nextInt();
        
        b= (x==y);
        System.out.println(b);
        
    }
}

Exercises

Please do not hesitate to send us your code via the comments section below. We will be happy to provide you feedback.

  1. Write a program that can say whether it is a hot day or not. Ask the user for the temperature (in Ferenhite) of the day. Print “true” if the temperature the user provides is higher than or equal to 90-degree Ferenhite. Print “false”, otherwise. Please do not use if-then-else for this program.
  2. Write a program that can say whether a number is odd or even. Ask for an integer from the user. Print “true” if the user enters an even number and “false” if the user enters an odd number. Please do not use if-then-else for this program. Hint: You will need to use the remainder (%) arithmetic operator.

Additional Resource

The following Java documentation covers relational and conditional operators. It uses if-then-else, which we have not covered yet in our videos. As a result, the link below might not make a whole lot of sense at this point. Still, we are providing it here as a standard reference because it is a part of Oracle Java documentation. The content of the following link will make sense after a few more video lectures.

Equality, Relational, and Conditional Operators

Comment

We will come back soon with the next topic. To stay in touch, please subscribe to Computing4All.com and subscribe to our YouTube channel. Enjoy!

Transcription of the Audio of the Video

Hi,
I am Dr. Shahriar Hossain. Today, I am going to explain the concept of Boolean variables. Boolean variables are capable of holding conditions. In a computer, a condition or a status is either “true” or false.

Logical conditions (to be used with relational operators)

A “condition” in Java refers to logical conditions of mathematics. For example, 10>5, or 6<10. Other than the “greater than” or the “smaller than” symbol, there are several other logical conditions. For example, equal to (==), not equal to (!=) greater than or equal to (>=), smaller than or equal to (<=) .

Relational operators

Here is a complete list of logical conditions
[Show on screen]
• a < b (a is Less than b)
• a <= b (a is Less than or equal to b)
• a > b (a is greater than b)
• a >= b (a is greater than or equal to b)
• a == b (a is equal to b)
• a != b (a is not equal to b)
[End of- Show on screen]

Equality comparison

Java recognizes equality comparison of two variables with two equals symbol (==). If you provide one equal symbol, it is considered as an assignment. Again, one equal symbol means assignment, that is, the right side of the assignment will be copied to the variable in the left side. Two consecutive equal symbols refer to “equality comparison” between two variables or numbers.

Each of these logical conditions results in either “true” or “false”. As a result, a Boolean variable is capable of remembering or holding the result of each of these logical conditions.

Boolean variables to store the results of relational operations

As I said earlier, a Boolean variable is a variable that can hold either true or false. In a computer, “true” refers to 1, and “false” refers to zero. In an earlier video, we explained data types and mentioned the ranges of number variables like integer, double, byte, so and so forth. The range of a Boolean variable is just zero and one, nothing else. Boolean is a data type that requires the smallest memory size, just one small bit. As a result, it can only hold either one or zero, in a small bit size.

Today we will see how we can declare a Boolean variable and what we can do with it. In this video, we are learning logical conditions as well. Logical conditions are comparisons. Comparisons will help us when we will learn conditional statements like if-then-else in a later video.

I will share my screen with you in a moment.

Starting of the code

My class name is BoolTest.java. I am writing my main methods, inside which I have declared a boolean variable named b. I also declare two more variables, x, and y, of integer type. I will ask the user to enter two numbers for x, and y. Therefore, I prepare my Scanner object named scan. I write code to get input for x. I also write code to get input for y.

At this point, I want to keep the information if x is greater than y in the boolean variable. Notice that the answer “if x is greater than y” is either yes, or now. Therefore, for the answer, you just need a Boolean variable because the Boolean variable has the capability to hold true or false, which is “yes” or “no” in this case.

If I type x>y the value is either true or false. If the content in x is greater than the content in y, then the value will be true, otherwise, the value will be false. I assign the value in the right side of the assignment operator to the variable I have on the left side. The variable I have on the left side is b, which is a Boolean variable.

Now let us print the status of the Boolean variable b, using a System.out.println statement. Save the file, compile, and run it. The program ask for the first number. The user enters 10. The program asks for the second number, the user enters 20. The program immediately answers false. Notice that the program only answers if the first number if greater than the second number the user has entered. Since 10 is less than 20, the statement “the first number is greater than the second number” is false. The program has printed false.

Running the program

Let us run the program again. The program asks for the first number. The user enters 50. The program asks for the second number. The user enters 10. Notice that the first number is greater than the second number. The program should now say true. This is because the first number is greater than the second number, and the program is checking if the first number, x, is greater than the second number, y.

Let us do another check now. Let us change the greater than symbol to smaller than. That is the program should output true if the first number is smaller than the second number. Save the file, compile it, and run it. The user enters 20 and 25 as the first and the second number. Since the first number, 20 which is x, is smaller than the second number, 25, which is y, the program outputs “true” now. That is, the program now checks if the first number is smaller than the second number.

I am quickly showing another example. Where you can see that the first number is 30 and the second number the user entered is 10. The program outputs false because the first number 30 is not smaller than the second number 10.

Changing the code with equality (==)

Now, we are going to examine another comparison operation, which is whether the content of two variables are equal or not. As I said earlier, the equality comparison between two variables is accomplished by two equal symbols. Therefore, if we write x two equals (==) y, the right side of the assignment operator should be true only when x is equal to y, otherwise, it should be false. That is, b will be true if x and y are equal. b will be false if x and y are unequal.

Sometimes, my students get confused because this particular line looks a bit weird due to three equals symbol. To reduce the confusion you can put parentheses on the right side of the assignment operator. The parentheses will not change anything. You can put them for clarity. I will skip them in my code. Let us save the file, compile it, and run it.

Running the code

10 and 20 are not equal. Therefore, the program outputs false.
20 and 10 are not equal. Thus, the program outputs false.
The user enters 10 and 10 as the first and the second number. The program outputs true now, which you expected because you used equality comparison in your code.

Let me quickly show you that putting those parentheses will not change the correctness of the program.

Notice that my program prints the same output, which is “true”, for equal inputs.

Concluding remarks regarding boolean variables and relational operators

The main idea of the video today is to familiarize you with the concept of Boolean variables and logical conditions. Over time, we will see more complex logical conditions, as well as conditional statements. Please practice what we have discussed today. For exercises, please visit the link provided in the description. Subscribe to this YouTube channel and to our website Computing4All.com. We do not assume that you know anything about programming. Our video lectures, so far, are prepared for beginners regardless of their backgrounds. Please start from the beginning of this lecture series if you are entirely a new learner.

See you in a few days in the next video lecture. Meantime, please do not hesitate to send us any question you may have, through the comments section below, or via the contact us form on our website Computing4All.com. Thank you very much for watching the video.