Flow Control Statements: if, for, while, switch and more

Introduction

Programming languages have flow control statements to change and control the behavior of the program during the execution, and it consists of conditions and statement blocks. 

The flow control statement will perform once the program evaluates the result of the statement condition, and if the evaluation is correct, a particular statement block or block of code will be executed, and later we will cover more about it on this tutorial.

Below is the list of the following statements that will cover on this tutorial, and there are three types of statements:

  • Decision-making statements:
    • if statement
    • if-else statement
    • switch statement
  • Looping statements:
    • for statement
    • while statement
    • do-while statement
  • Branching statements:
    • break statement
    • continue statement
    • return statement

This tutorial will use java as an example programming language, and at the beginning of each example, you will see a flow chart that will help to illustrate and explain the examples. (refer to this link for more info about flow chart: http://lgeratech.com/2020/04/flow-chart/)

Decision-making statements

The introduction section was mentioned about the conditions and statement blocks, however, this section will be the continuation of that topic.

The decision-making statement contains conditions and statement blocks, the condition will only fall into two results it’s either true or false, and the statement block will only execute once the result of the condition is true.

Flow Chart

As you can see in the image above, the condition has two paths, a path for statement 1 and statement 2, if the condition is equal to true the statement 1 will be executed, and statement 2 if it’s equal to false.

If statement

The if-statement is one the most helpful and manageable statement in programming languages, and it is easy for you to learn if you are a beginner, this statement handles only one condition and one statement block, and only check the correct result.

If statement syntax structure:

if ( condition ) {

    statement block…

}

The condition will always inside of pair brackets, an opening bracket before it, and a closing bracket after it, for the statement block, it is cover with pair of curly brackets.

Here is the example if-statement:

In the table above we list down all the requirements for the scoring system before we convert those requirements to program, we should try to illustrate it to flow chart first, to visualize the possible scenarios of the code:

Let say we have a score of 50%, what will be the output of our if statement?

Flow Chart

Let’s apply the flow chart in the java program to see the results, as you can see in the above, the flow chart has three decisions symbols, in the program, we should create if-statement for each decision:

  • First if condition: check the score if greater than and equal to 80
  • Second if condition: check the score if greater than and equal to 40 and less than to 80
  • Third if condition: check the score if less than to 40
public class ScoringSystem {
	public static void main(String[] args) {
		int score = 50;
		if(score >= 80) {
			System.out.println("Three Star: * * *");
		}
		if(score >= 40 && score < 80) {
			System.out.println("Two Star: * *");
		}
		if(score < 40) {
			System.out.println("One Star: *");
		}
	}
}

Output: Two Star: * *

If you don’t know how to compile code yet, you can refer to this post for the java basics and installation: http://lgeratech.com/2020/01/java-core-programming-in-2020/

If-else statement

The if-else statement is a part of the if statement, let say it is an extension of it, in the last section, if-statement only executes a block of codes when the condition is equal to true, however, applying if-else statement can perform codes when the condition is false.

For the example in if-statement, we use three conditions to check the scoring requirements, in this section, we will update that example to see the difference of using the if, and the if-else statement:

Flow chart

As you can see, the flow chart will lessen the decisions if we apply the if-else statement, in java program, it will look like this:

public class ScoringSystem {
	public static void main(String[] args) {
	int score = 39;
		if(score >= 80) {
			System.out.println("Three Star: * * *");
		}else if(score >= 40 && score < 80) {
			System.out.println("Two Star: * *");
		}else{
			System.out.println("One Star: *");
		}
	}
}

Output: One Star: *

In the example code, it not only reduces the conditions but also it will help you to lessen the effort in the programming.
In this example, it has two conditions the check the following requirements for scoring if those conditions do not fulfill the requirements the else block will execute.

switch statement

The switch statement consists of multiple conditions, and it is also known as a selection control mechanism, it only selects condition that has a correct result, and the result is based on the variable pass to the root of the switch statement.

Switch statement syntax structure:

switch(condition value...){
	case (condition...):
		//statement block...	
		break;
	case (condition...):
		//statement block...	
		break;
	case (condition...):
		//statement block...	
		break;
	default:
                //statement block...	
		break;
}

This statement will be various compared to if statement and if-else statement, so there will be little changes to the example we used in the last section to see the different use of this statement, see the below table for the details:

Flow Chart

As you can in syntax structure section, the switch value will place inside of pair brackets. Therefore, the multiple cases or conditions are placed inside of pair curly brackets. And then each case has a statement block to execute a particular block of code.

The switch cases also used another statement called break statement. Therefore, it stops the switch from selecting or evaluating the other cases after it chooses the correct one. (refer to the branching statements section for more info about break statement)

And also switch statement has default condition, if there is no selected case the default statement block will be executed.

Let’s convert the flow chart to a java program again, to see the result of it:

public class StarScoringSystem {
	public static void main(String[] args) {
		int star = 2;
		switch (star) {
		case (3):
			System.out.println("A");
			break;
		case (2):
			System.out.println("B");
			break;
		case (1):
			System.out.println("C");
			break;
		default:
			break;
		}
	}
}

Output: B

Looping statements:

This type of statements are used to execute one or more blocks of code repeatedly. Therefore, the loop execution will only stop when the condition is equal to false. And there are three types of looping statements, for, while and do-while statement.

Flow Chart

The looping statement also contains a condition to control the loop. Imagine without condition, it will execute repeatedly and never stops. Therefore. one thing also that can cause an infinite loop when the condition never returns false.
As you can in flow chart above, it is the same on what I’ve mentioned. However, if the condition turns false, the execution will stop.

For statement

The for-statement or for loop is the most commonly used in the algorithm. Including data structure, and some logical and mathematical computation. Technically, it contains conditions, statement blocks, and incremental or decremental value, to take control of the repeated execution.

For statement syntax structure:

for( Initial counter value ; condition ; increment or decrement counter value ){
statement block…
}

In the above for-loop syntax, the codes inside of an opening and closing brackets have three section blocks for counter and condition, and the executable section of the code is inside of pair curly brackets.

Here is the example code, let’s print 1 to 10 numbers:

Flow Chart

In flow chart illustration, there is a variable named counter and the initial value is 1, this variable will serve as a controller of the for loop process flow: 

  1. Once the loop is started, the condition will check the counter value, if it’s less than, or equal to 10.
  2. If the condition is correct, the program will print the counter value.
  3. Once the counter is printed, the value will increment (without incrementing the counter value, the condition will always return true, and the loop will never stop).
  4. The process 1, 2, and 3 will be repeated when the condition is not turning to false, however, if it is false, the for loop will stop.

Java Code:

In for loop program, the counter variable declaration in incrementation can be embedded to itself, so no need to declare the counter outside of the for loop, see the example code below:

public class ForLoop {
	public static void main(String[] args) {
                int max_iteration = 10;
		for (int counter = 1; counter <= max_iteration; counter++) {
			System.out.println(counter);
		}
	}
}

Output:
1
2
3
4
5
6
7
8
9
10

While statement

While-loop is also based condition statement, compared with the for-loop, while-loop doesn’t have an embedded counter variable in the program, as long as the condition is true the while-loop will execute the particular block of code repeatedly.

Let’s reuse the example in for-loop, as you can see below, the counter variable is declared outside of the while program, then increment the value inside of the execution block:

public class WhileLoop {
	public static void main(String[] args) {
		int max_iteration = 10;
		int counter = 1;
		while (counter <= max_iteration) {// condition check if the counter is less than or equal to max_iteration
			System.out.println(counter);// print value
			counter++;// increment value ++ means plus 1 
		}
	}
}

Output:
1
2
3
4
5
6
7
8
9
10

Do-while statement

Do while loop is part of while loop statement if you extend do-while in your while loop, it will change the execution, do-while will execute the block of code first before checking the condition, here is the new illustration for do-while example:

As you can see, the program executes the block of code first which is printing and increment the value of the counter, after that, the program evaluates the condition, in the source code this is how the do-while works:

public class WhileLoop {
	public static void main(String[] args) {
		int max_iteration = 10;
		int counter = 1;
		do {
			System.out.println(counter);
			counter++;
		} while (counter <= max_iteration);
	}
}

Output:
1
2
3
4
5
6
7
8
9
10

In the java program, the do-while statement executes the code first before evaluating the condition, which is inside of the do keyword with curly brackets, if the condition is true the do section will execute again.

Branching statements:

Branching statements are used to change the execution behavior of a regular flow of looping statements, and it can change the behavior by jumping to other part of the program or changing the execution based on the conditions.

This type of statement doesn’t have a condition or execution block in programming language, and it can only apply inside of looping statements or decision-making statements.

Break statement

This statement is used to terminate the control statement and move to other statement or block of codes.

We already applied the break statement in the switch statement section, and we used it to terminate the execution inside of the switch statement. 

Break statement syntax structure:

break;

Let’s apply the break statement in for loop statement:

Flow Chart:

In the example above, the for loop prints 1 to 10 counter value, but when we add nested if-statement to check if the counter value is equal to 5, then if the condition is true, the program will execute the break statement to terminate the for loop statement.

Java program:

public class ForLoop {
	public static void main(String[] args) {
        int max_iteration = 10;
		for (int counter = 1; counter <= max_iteration; counter++) {
			if(counter == 5) {
				break;
			}
			System.out.println(counter);
		}
	}
}

Output:
1
2
3
4

Like the flow chart illustrated to you, the loop will stop if the counter value is equal to 5, so that why the output ends at 4.

Continue statement

It is mostly used in looping statements, and it will control the loop iteration by skipping the current execution based on the decision made using if statement if the statement corrects the loop jumps to another iteration to execute a block of code.

Continue statement syntax structure:

continue;

Flow Chart

Java program:

public class ForLoop {
	public static void main(String[] args) {
        int max_iteration = 10;
		for (int counter = 1; counter <= max_iteration; counter++) {
			if(counter == 5) {
				continue;
			}
			System.out.println(counter);
		}
	}
}

Output:
1
2
3
4
6
7
8
9
10

As you can see in illustration and java program, the condition checks if the counter value returns 5, if it is correct, the loop will execute the continue statement and skip printing the counter value 5, that’s why number 5 in the output is missing.

Return statement

The return statement has similarity to the break statement, it can terminate execution, however, unlike the break statement, it can only use in function or method in java, and it has a return value.

The return value produces by calling the function, it can control the program by resuming the function results in other rounds of execution somewhere in the program.

Let’s use the example in the continue statement, but here we don’t need to illustrate it on the flow chart, see the example code below to see the difference:

public class ForLoop {
	static boolean validateCounterValue(int counter) {
		if(counter == 5) {
			return true;
		}
		return false;
	}
	public static void main(String[] args) {
        int max_iteration = 10;
		for (int counter = 1; counter <= max_iteration; counter++) {
			if(validateCounterValue(counter) == true) {
				continue;
			}
			System.out.println(counter);
		}
	}
}

As you can see, we added function named validateCounterValue, and we placed it inside of the for loop thru the used of if statement to check if the counter value is equal to 5 if it is true, the function will return true and the program will continue the execution after returning the value.

Conclusion

Java language executes the program from top to bottom, however, it is necessary to the developers use flow control statement to break the natural flow of the program by controlling the execution, you can apply it by implementing decision making, looping, and branching to your programs, and with the help of this statements, we can execute a particular block of codes, anywhere and anytime we want in our programs.

Learning from this tutorial is not only beneficial in java, but also to other programming languages if you are a beginner, and seeking other languages to study coding, it is useful to you since java has a similarity to other programming languages in terms of flow control statements like C#, C++, Python and more.

One thought on “Flow Control Statements: if, for, while, switch and more

  • off white clothing
    August 9, 2020 at 9:32 pm

    I抎 need to examine with you here. Which isn’t something I normally do! I get pleasure from reading a put up that can make folks think. Additionally, thanks for allowing me to remark!

Leave a Reply

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

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

BCF Theme By aThemeArt - Proudly powered by WordPress.
BACK TO TOP