Tuesday, 16 May 2017

Tutorial 10: Flow Control


Flow Control


The flow control functionality in Java does just that: it controls the flow of your programs. Using flow control structures, you can use boolean statements to determine what the program does. For example, let us say that you want to divide two numbers x and y. We know that when we do x/y, if y is zero, we will get an error. So we might want to check whether y is 0. If it is zero, we might want to force the program to return 0. If y is not zero, then we might want to continue with the operation. The following are examples of flow controls in Java. I will discuss each and give an example to illustrate what I mean.

If-Else


The if-else construct looks like this:

if (condition) {

}

else {

}

Let us look at a real example: Let’s say we want to check whether a number is positive and if it is positive, print out that the number is positive on the console. Otherwise (that is, the number is negative), we want to state that the number is negative on the console. This is how you do it.

int j = 5;

if (j > 0) {

            System.out.println(j + “ is a positive number.”);

}

else {

            System.out.println(j + “ is a negative number.”);
}

Figure 1: A simple if-else statement program.


Now, what if you would like to have many conditions in your program? Let’s look at an example. Let’s say, you want to determine the grade that a student got based on their marks. Now we can assume that between 0 and 39 if an F, between 40 and 49 is a D, between 50 and 59 is a C, between 60 and 69 is a B, and anything above 70 is an A. Now you see, we have to modify our if-else statement like this:

int grade = 72;

if (grade >= 0 && grade <= 39) {

            System.out.println (“F”);

}

else if (grade >= 40 && grade <= 49) {

            System.out.println (“D”);

}

else if (grade >= 50 && grade <= 59) {

            System.out.println (“C”);

}

else if (grade >= 60 && grade <= 69) {

            System.out.println (“B”);

}

else if (grade >= 70 && grade <= 100) {

            System.out.println (“A”);

}

else {

System.out.println (“Invalid grade”);
}

Figure 2: If-else statement with the else-if construct.


So here, we introduce else if which we can use to check whether or not the conditions are true or false and then either execute them or ignore them. With the last statement: else {System.out.println (“Invalid grade”); we check to see whether the grade entered is correct. You see, someone could enter a grade of 1000 marks and this is not acceptable because we only have a maximum of 100%. The above program ensures that only values between 0 and 100 are entered. Any other beyond or below these boundaries is not acceptable.

Do-While


The do-while construct looks like this:


do {

statements;

} while (condition);

By the way, remember that condition is a boolean statement.

This is how the above construct works: Java will first execute whatever statements are within the do curly braces i.e. do {statements;} and then check the condition i.e. while(condition);


If the condition is true, it will execute the statements again. Then, it will check to see if the condition is true. In case the condition has become false, Java will stop executing the do-while code.


So you see, Java will always execute the statements in the do {statements;} body once even if the condition if false. Why, because before checking whether or not the condition is true, this construct requires that the code within the do curly braces is run. Beyond that, it will continue running of the condition is true and stop otherwise.


Let me show you that do-while executes at least once, even if the condition is false: Let’s say that we want the program to print “I am a positive number” to the console, even when the number is negative. 

int j = -1;

do {

            System.out.println(“I am a positive number”);
} while (j > 0);

Figure 3: A program that shows that a do-while statement always runs at least once even if the condition is false.


So as you can see from the above program, you really need to be careful because a do-while will always execute once before checking the condition. After printing out “I am a positive number” on the console, Java checks the condition and finds that it is false, and exits from the loop. The above illustration is an example of unexpected results.


Also, unless you want to run an infinite loop, or a loop that never ends, you need to think about your condition. Normally, you want a condition that is true for a certain range that then becomes false, and exiting the loop.

If you do the following, for example, you will end up with a program that loops forever:

int j = 1;

do {

            System.out.println(“I am a positive number”);
} while (j > 0);

Figure 4: An example of an infinite do-while program. As you can see, the program runs indefinitely unless stopped.


You see here that j is greater than 0. The program will print “I am a positive number” to the console indefinitely because the condition while (j > 0); will never be false.

While


The while construct looks like this:

while (condition) {

            statements;

}

Java will first check the condition to determine if it is true or false. If it is true, it will execute the statements within the curly braces until condition becomes false. If the condition is false, Java will not execute the statements within the curly braces.


Now, can you tell the difference between the do-while construct and the while construct?


The difference is that the do-while construct will always execute once even if the condition is false. However, if the condition in the while construct is false, the statements within the curly braces will not be executed.


Here is an example of the while construct. Let’s say that we have an int j that is equal to 0. We want Java to increment j by one during each loop and only stop when j is equal to 10. Here is how we do it:

int j = 0;

while (j <= 10) {

            System.out.println(j);

            j++;
}

Figure 5: An example of a program that uses a while loop to print a list of numbers on the console.


Also, unless you want to run an infinite loop, or a loop that never ends, you need to think about your condition. Normally, you want a condition that is true for a certain range that then becomes false, and exiting the loop.

For example, if we write the above program as follows, it will run indefinitely:

int j = 0;

while (j == 0) {

            System.out.println(j);
}

Figure 6: An example of an infinite while loop. The program runs indefinitely unless interrupted.


As you can see, j is equal to 0. The condition tells Java to print the value of j, which is 0, to the console as long as j is 0, which it is. So if not interrupted, the above program will run forever.

Switch


The switch construct looks like this:

switch (value) {

            case 1: statement;

                        break;

            case 2: statement;

                        break;

            case 3: statement;

                        break;

            default: statement;

                        break;

}

Let’s explore the above construct using an actual example: Assume we have a month that is fifth on the calendar…. Okay, who are we kidding? We know that the fifth month is May.


But what if we didn’t know the name of month number 5 and we wanted a program to help us decide. Here is how we could do that using the switch construct:


int month = 5;

switch (month) {

            case 1: System.out.println (“January”);

                        break;

case 2: System.out.println (“February”);

            break;

case 3: System.out.println (“March”);

            break;

case 4: System.out.println (“April”);

                        break;

case 5: System.out.println (“May”);

                        break;

case 6: System.out.println (“June”);

                        break;

case 7: System.out.println (“July”);

                        break;

case 8: System.out.println (“August”);

                        break;

case 9: System.out.println (“September”);

                        break;

case 10: System.out.println (“October”);

                       break;

case 11: System.out.println (“November”);

                       break;

case 12: System.out.println (“December”);

                       break;

default: System.out.println (“Invalid month!”);
}



Figure 7: A program that uses switch. Results are on the right panel.


So what Java does in the above example, is it checks the value in switch (value) and compares it to the case statement within the curly braces until it finds a match. In this case, value is the integer month, to which we assigned the value 5. So Java will look until it comes to case 5: System.out.println (“May”); and it will print “May” to the console.

In case Java doesn’t find a matching statement among the cases, it will execute the default, which in the above example is default: System.out.println (“Invalid month!”); Try to change the value of month to and see what happens.

The break keyword tells Java where a case statement reaches. Therefore, we can use the break statement to group together related case statements. For example, let’s say that we want to group the months of the year into quarters. We know a quarter has three months and that the whole year has four quarters. So how do we create a program that tells us to which quarter a month belongs?

int month = 5;

switch (month) {

            case 1:

            case 2:

            case 3: System.out.println (“First quarter”);

                        break;

            case 4:

            case 5:

            case 6: System.out.println (“Second quarter”);

                        break;

            case 7:

            case 8:

            case 9: System.out.println (“Third quarter”);

                        break;

            case 10:

            case 11:

            case 12: System.out.println (“Fourth quarter”);

                        break;

            default: System.out.println (“Invalid month!”); 
}




Figure 8: An example of a program that uses switch. This program demonstrates the importance of the break statement.

For loop


The for loop looks like this:

for (initialization; condition; increment/decrement) {

            statements;

}

These are the parts of a for loop:

a) initialization – This is the part where you give your values the initial values.

b) condition – This is the condition that Java will check and run the code within the curly braces if true. It will repeat or loop this code until condition becomes false.

c) increment/decrement – This tells Java what to do with the values we initialized in the initialization stage in (a) above.

So let is look at an example: Let’s say we want to use the for loop to print the value of an integer j on the console as it is incremented by one, and then stop when j is 10. We do it like this:

for (int j = 0; j <=10; j++) {

            System.out.println(j);
}


Figure 9: A program that uses the for loop to print incremental numbers to the console.


What if we would like the program to decrement an integer value i initialized as 10 and print to the console its value each time it gets decremented? Here is how we do it:

for (int i  = 10; i >= 0; i--) {

            System.out.println(i);
}


Figure 10: A program that uses the for loop to print detrimental numbers to the console.

Nested for loops


There are cases where we can have one for loop within another for loop. This is referred to as a nested loop.

The concept of a nested for loop is one which I struggled with for a long long time before I could understand what was going on. But with persistence, I finally got my head around it.

This is how a nested for loop looks like:

for (initialization; condition; increment/decrement) {

            for (initialization; condition; increment/decrement) {

                        statements;

            }

}

Let’s look at an example and then I’ll explain what’s going on:

for (int i = 1; i <= 2; i++) {

            for (int j = 10; j >= 0; j--) {

                        System.out.println(“the value of j is: ” + j);

}
}

Figure 11: As you can see in the above program, the inner loop runs twice because the outer loop says for (int i = 1; i <= 2; i++) {


As you can see from the outcomes running this program, the outer for loop determines the number of times the inner loop executes. This is all you need to remember. So, in the above example, if I change the outer for loop to look like this: for (int i = 1; i <= 10; i++) {, then the inner loop will only run 9 times before the condition of the outer loop becomes false and program execution stops.

Infinite for Loops

Let’s say you want to create a for loop that will run forever, or in other words, for as long as the program is running. How do you define it? Here’s how you do it:

for (; ; ) {

            statements;

}
For example, say I want to print a value on the console indefinitely. Here is how I would do it:

for (; ; ) {

            System.out.println(“I am an infinite loop”);
}



Figure 12: An example of a program with an infinite for loop.


The above program will continue running until you shut down the computer, or the memory is full or the program exits. If left alone, it can literally run forever.

So, the above pretty much covers flow control structures in Java. I would encourage you to keep practicing whatever you read, because that is how you learn.


In case of any question or comment, please leave them in the comment section below and I will make sure to address them. 


In the next tutorial, we will look at constructors in more detail.

Until then, stay safe.





No comments:

Post a Comment