Controlling Program flow

There are moments when an action is required to take place, after a condition is met. Control statements are used in such situations to control the flow of execution of a program, based on certain conditions. Some example of control statements are shown below. A group of control statements called selection statements are shown below. They used to decide whether a certain statement or block of statements will be executed or not. Examples of selection statements are shown below.

if statement is the simplest selection statement. When used with a condition, it decides whether a block of statements will be executed  if a condition is met, or not if a condition is not met. Example below:

Define and initialise variables to be used in a condition   

int one = 1, two = 2;

Define a condition to test if two is greater than one 

boolean twoISgreater = two > one;

Define the block of statements to execute, if condition is true

String soTrue = “””

           The number two is greater than one.

           one + two equals

           “”” + (one+two) ;

Use the if statement to test the condition and if true execute and print the block of statements

if(twoISgreater) {

      System.out.println(soTrue);   

  } 

if/else statement is a selection statement that executes a block of code when a condition is met, else it executes another block of code when condition is not met. Example below determines if a number is even or odd:

Define and initialise a variable for the user input data.

int number = 3;

Define a condition used to determine if the user input number is an even number.

boolean even = (number%2 == 0);

Use if/else statement to evaluate if number is an even number, else an odd number.

if(even){

          System.out.println(number+” is even”);

     } else {

System.out.println(number+” is odd”);

     }

Nested if statement is an if statement that is inside an if statement. It can be used to zero-in on a subset of data under consideration.When the if condition is met, the if block is executed and then the nested if condition is evaluated and if true, it’s block of code is executed. The example below accepts only positive integer input, else it converts the input into a positive integer:

Define and initialise a number variable . 

double number = -3.9d;

Define and initialise the output variable 

int integer = 0;

Apply if else and nested if to the number

if(number%2 == 0 || number%2 == 1){                                                

integer = (int)Math.floor(number);                                        

if(integer >= 1){                                                      

System.out.println(“number in nested if is “+integer);

 }

}else{

integer = -(int)Math.floor(number);

if(integer >= 1 || number%2 == 0){

System.out.println(“number in else is “+integer);

}    

if-else-if ladder is used to make a decision when there are multiple options. The if statements are executed from the top down. When an if conditions is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement is executed. Example is shown below:

Define and initialise a variable to represent a question

String question = “What is the Capital city of USA ?”;

Define user inputs in which one represent the correct answer to the question

String input = “Washington DC”;

String input2 = “London”;

String input3 = “Berlin”;

String input4 = “Paris”;

Apply the if-else-if statement to determine the correct answer.

if(input == answer ){

System.out.println(input + ” is correct”);

}else if(input2 == option2) {

System.out.println(“input 2 is incorrect”);

}else if(input3 == option3) {

System.out.println(” input 3 is incorrect”);

}else if(input4 == option4) {

System.out.println(“input 4 is incorrect”);

}else {

System.out.println(“No answer to the “+question+” is correct “);

}

Switch Statement                                                                         

The switch statement is a multiway branch statement that dispatch execution to a particular branch of code based on the value of an expression. Each branch of code is made up of a case value and a statement value. Example is shown below:

Define and initialise a variable representing an age that will be used as an expression

int age = 18;

Use the age expression in a switch statement and include key value pairs that represent case and statement. The break statement after each case and statement is used to stop further execution when a case is equal to the expression. the default statement is used when no case is valid.

switch(age){

           case 19 : System.out.println(“Age is “+age);

                    break;

           case 18 : System.out.println(“Age is “+age);

                   break;

        default : System.out.println(“Age is not present”);       

      }

Jump statements are break, continue and return. These three statements direct control to a different part of the program.

break Statement is a type of jump statement used for terminating a switch statement when a case evaluates to the expression. it can also be used to exit a loop or as a form of directing control to another part of a program.

Continue Statement is a type of jump statement that is used to bypass data that meets a condition but process data that do not meet that condition. Example is shown below:

if number represented by i is even then skip it using the continue statement and then print the odd numbers 1 3 5 7 9.

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

           if (i % 2 == 0)

                continue;

          System.out.print(i + ” “);                                            

}

return statement is used to return control back to the caller of the method. Example is shown below:

Define a method that takes a number and use return to send number multiplied by 2 back to the caller

static int numberByTwo(int number) {

      return number * 2;   

}

Loops Looping is a feature that allows the repeated execution of a set of instructions while a condition evaluates to true. Java provides Three types of Loop statements namely while loop, for loop and do while.

for loop is divided into the following parts namely Initialization Expression, Test Expression, Update Expression and body of Loop.  Initial expression is a variable initialised to a value, which acts as a counter for the starting point of the loop. expression is a condition that will be tested. If the condition evaluates to true then, the body of the loop is executed, after which control goes to the update expression and then again  the  test expression  and execution of the loop body is repeated. If the condition evaluates to false, then the for loop exits. Example of the for-loop statement is shown below:

Define the initialisation variable as: int counter = 0;                                                            Define the Test condition as: counter <= 10; 

Define the body of the loop as: System.out.println(counter);                       

Define increment statement as: counter++ ;                                               

Write the loop statement with initialisation variable, Test condition, body statement and increment statement:

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

           System.out.println(counter);                                     

 }    

The output is 0 1 2 3 4 5 6 7 8 9 10

while loop is a control statement that allows repeated execution of code based on a boolean condition.  The while loop is similar to a repeating if statement. Example below:

Define and initialise a counter to be used as a control for the number of loops.

int counter = 0;

Define the while loop using the counter to prevent endless loop.

while(counter <= 10) {

       System.out.print(counter + ” “);

        counter++;

     }

do while loop executes the statements first, then checks the condition. The loop continues until the condition evaluates as false. Example below:

Define a counter to control number of loops                                           

int counter = 10;

Define do while loop using the counter to print out 10 9 8 7 6 5 4 3 2 1

do {

       System.out.print(counter + ” “);

           counter–;

        }while(counter >= 1);

For a complete knowlege of Java see the book preview below:

Preview Java Beginner Reference Book

                                                               

                             

  

Leave a Reply

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