Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
33 views8 pages

06 Handout 1

The document provides an overview of control structures in Java, including selection, repetition, and branching statements. It explains the syntax and usage of various control statements such as if, if-else, switch, while, do-while, for loops, and branching statements like break, continue, and return. Examples are included to illustrate how these control structures function within Java programming.

Uploaded by

tgvgyuhbgyh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views8 pages

06 Handout 1

The document provides an overview of control structures in Java, including selection, repetition, and branching statements. It explains the syntax and usage of various control statements such as if, if-else, switch, while, do-while, for loops, and branching statements like break, continue, and return. Examples are included to illustrate how these control structures function within Java programming.

Uploaded by

tgvgyuhbgyh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

IT2402

CONTROL STRUCTURES
A program performs decision-making to determine the sequence in which it will execute the instructions.
Control statements are used to control the execution flow of the program. The execution order of the
program is based on the supplied data values and the conditional logic. Java supports the following types of
control statements: Selection, Repetition, and Branching.

Selection (Agarwal & Bansal, 2023)


Selection statements are decision-making statements that include if, if-else, and switch statements.

if statement
The if decision construct is followed by a logical expression wherein data is compared, and a decision is
made depending on the comparison result.

This statement has the following syntax:


if (boolean-expression){
statements;
}

For example:
int a=16;
if (a%2==0){
System.out.println("This is an even number");
}

The example lets the program decide whether the output matches the condition of the Boolean expression.

if-else statement
It is an extension of the if statement that provides an alternative action when the if statement results in a
false outcome. The else block is executed whenever the if statement is false. A block is the set of
statements between two curly braces ({, }).

This statement has the following syntax:


if (boolean-exprsn){
statements;
}
else{
statements;
}

For example, a code determines whether aNum1 or aNum2 holds a higher value.
if (aNum1 > aNum2){
aMax = aNum1;
}
else {
aMax = aNum2;
}

06 Handout 1 *Property of STI


[email protected] Page 1 of 8
IT2402

If the value of aNum1 is greater than that of aNum2, the statement in the if block is executed; otherwise, the
statement in the else block is executed.

Extending the if statement example with an else block in case the condition of the if statement is not met
or if it is false.
int a=16;
if (a%2==0){
System.out.println("This is an even number");
}
else {
System.out.println("It is an odd number");
}

switch statement
It is considered an easier implementation of the if-else statement. It is used whenever there are multiple
values possible for a variable. This statement successfully lists the value of a variable or an expression
against a list of byte, short, char, or int primitive data types only. The statements linked with that case
constant are executed when a match is found.

The syntax includes:


1 switch (variable-name)
2 {
3 case exprsn1:
4 statements;
5 break;
6 case exprsn2:
7 statement;
8 break;
9 case exprsn3:
10 statement;
11 break;
12 default:
13 statement;
14 }

The switch keyword is followed by the variable in parentheses, such as in line 1.

Each case keyword found in lines 3, 6, and 9 is followed by a case constant (exprsn1/2/3). The data type of
the case constant must match that of the switch variable. Before entering the switch construct or
statement, a value should be assigned to the switch variable.

The break statements in lines 5, 8, and 11 are used to cause the program flow to exit from the body of the
switch control. Control goes to the first statement following the end of the switch construct. If unused, the
control passes to the next case statement and the remaining statements are also executed.

06 Handout 1 *Property of STI


[email protected] Page 2 of 8
IT2402

The statement associated with the default keyword such as in line 13 and line 12, respectively, is executed
if the value of the switch variable does not match any of the case constants. Take note of the following:
• The default label must always be the last option in the switch construct if used
• The case expressions can be of either numeric or character data type
• The case constants in the switch statement cannot have the same value

For example, the expression “day” in switch statements evaluates to “5,” matching with the case labeled “5.”
The code in case 5 is executed and results in the output “Friday” on the screen.
int day=5;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid entry");
break;
}

Repetition (Agarwal & Bansal, 2023)


Repetition statements are looping statements that include while, do-while, and for statements.

A loop causes a section of a program to be repeated based on the specified number of times. This repetition
continues while the condition set for it remains true. Otherwise, the loop ends and the control is passed to
the statement following the loop construct.

while loop statement


It is a looping construct that continues until the evaluating condition becomes false. The evaluating condition
must be a logical expression and must return a true or a false value. The variable checked in the Boolean
expression is called the loop control variable.

06 Handout 1 *Property of STI


[email protected] Page 3 of 8
IT2402

The syntax goes as follows:


while (boolean-exprsn)
{
statement;
}

The if statement and the break and continue keywords can be used within the while block to exit the loop.
For example, a code that generates the Fibonacci series, wherein each number is the sum of its two
preceding numbers. The series starts with 1.
Output:

public class FibonacciDemo {


public static void main (String a[]) {

int i1 = 1, i2 = 1;
System.out.println(i1);

while (i1<=i2)
{
System.out.println(i2);
i2+= i1;
i1=i2-i1;
}
}
}
Figure 1. Fibonacci results. Retrieved from Agarwal, S. &
Bansal, H. (2023). Java in depth. BPB Publications.

do-while loop statement


Another looping statement that lists the conditions after the statements to be executed. This statement can
be considered a post-test loop statement. First, the do block statement is executed, and then, the condition
given in the while statement is checked. In this case, even if the condition is false in the first attempt, the
do block is executed at least once.

The syntax goes as follows:


do
{
statement;
} while (expression);

See the example below.


int j=1;
do
{
System.out.println(j);
j++;
} while (j<=10);

06 Handout 1 *Property of STI


[email protected] Page 4 of 8
IT2402

The do block is executed first and the current value “1” is printed. Then, the condition j<=10 is checked.
After checking, “1” is less than “10,” so the control comes back to the do block. This process continues until
the value of j becomes greater than 10.

The while and do-while loops are used whenever the number of repetitions or iterations is unknown.
Iterations refer to the number of times the loop body is executed.

for loop statement


Compared to while and do-while statements, the for loop statement is used when iterations are known in
advance. This looping statement can be used when determining the square of each of the first ten numbers.

The syntax goes as follows:


for (initialization-exprsn; test-exprsn, increment_exprsn);
{
statement;
}

The for statement consists of the for keyword followed by parentheses containing three expressions
separated by a semicolon. These expressions are the initialization expression, the test expression, and the
increment/decrement expression.
• Initialization – gives the loop variable an initial value. This expression is executed only once when
the control is passed to the loop for the first time.
• Test – executes the condition each time. The control passes to the start of the loop. The loop's body
is executed only after the condition has been checked. If the condition is true, the loop is executed.
Otherwise, the control is passed to the following statement.
• Increment/Decrement – this expression is always executed when the control returns to the
beginning of the loop.

These expressions are understood by the compiler; thus, writing the name of the expression is not needed.
For example, in a statement:
for (invar=o; invar<=10; invar++)
o invar is the loop variable
o invar=o is the initialization expression
o invar<10 is the test expression
o invar++ is the increment expression

For all the parts, take this code snippet that calculates and prints the square of the first ten natural numbers
as an example.
int invar;
for (invar=1; invar<=10, invar++)
{
System.out.print(invar*invar)
}

06 Handout 1 *Property of STI


[email protected] Page 5 of 8
IT2402

The output of this is 1, 4, 9, 16, 25, 36, 49, 64, 81, and 100. The body of the for loop is enclosed within curly
braces. A common mistake programmers should avoid is terminating the for loop with a semicolon.
int invar;
for (invar=1; invar<=10, invar++);
{
System.out.print(invar*invar);
}

Since the for statement ends with a semicolon, it becomes a self-executing for loop that moves to the next
statement only when the condition in the loop becomes false. The for loop is exited when the value of
invar is 11; thus, the output is 121 from (11*11).

Branching (Agarwal & Bansal, 2023)


These statements transfer control to another part of the program.

break statement
It is a branching statement that can be labeled or unlabeled. This statement is used for breaking loop
executions such as of while, do-while, and for. It also terminates the switch statements.

The syntax includes:


• break; – which breaks the innermost loop or switch statement.
• break label; – which breaks the outermost loop in the series of nested loops. A nested loop is a
loop that exists within another loop.

Nested loop example: A for loop nested in if-else statement.
System.out.print("Enter a range of loop greater than 0: ");
int range = console.nextInt();
if (range > 0) {
System.out.println("The output of the loop is: ");
for (int i = 1; i <= range; i++) {
System.out.println(i);
} //end of for loop
} else {
System.out.println("The entered number is invalid.");
} //end of if…else statement

Another nested loop example: A nested for loop


int x, y;
System.out.println("Multiplication Table of 1-10:");
for (x = 1; x <= 10; x++) {
for (y = 1; y <= 10; y++) {
System.out.print(x * y + "\t");
} //end of inner for loop
System.out.println();
} //end of outer for loop

06 Handout 1 *Property of STI


[email protected] Page 6 of 8
IT2402

For the break statement example, when the if statement results in true, it prints “data is found” and comes
out of the loop immediately and executes the statement just following the loop.
public class BreakDemo
{
public static void main (String a[ ]){
int num[]={2,9,1,4,25,50};
int search=4;

for(int i=1;i<num.length;i++)
{
if(num[i]==search)
{
System.out.println("data is found");
break;
}
}
}
}

The output of this becomes:

Figure 2. Break statement. Retrieved from Agarwal, S. & Bansal, H. (2023). Java in depth. BPB Publications.

continue statement
It is used in looping statements such as while, do-while, and for to skip the current iteration of the loop
and resume to the next iteration.
continue; is used as the syntax of this statement.

06 Handout 1 *Property of STI


[email protected] Page 7 of 8
IT2402

For example:
public class ContinueDemo {
public static void main (String a[] ){

int num[]={2,9,1,4,25,50};
int search=4, found;

for(int i=1;i<num.length;i++){
if(num[i]!=search){
continue;
found=num[i];
}
System.out.println("data is found");
}
}
}
In this example, the expression found=num[i]; is unreachable because of the continue statement. It skips
the statement written after the continue statement and resumes the next iteration.

return statement
It transfers the control to the caller of the method. It is used to return a value to the caller method and
terminates the execution of the method. It has two forms: one that returns a value and the other that
cannot return a value. The returned value type must match the return types of the caller method.

The syntax includes:


• return values;
• return; – returns nothing, so this can be used when a method is declared with a void return type.
• return expression; – returns the value evaluated from the expression.

For example:
public static void hello() {
System.out.println("Hello "+ welcome());
}
static String welcome() {
return ("Welcome to Java Programming");
}
In this example, the welcome() function is called within the println() function, which returns a string value
"Welcome to Java Programming" which is printed to the screen.

References:
Agarwal, S. & Bansal, H. (2023). Java in depth. BPB Publications.
Burk, S. (2023). Java programming: The complete beginner’s guide. Orchid Publishing.

06 Handout 1 *Property of STI


[email protected] Page 8 of 8

You might also like