Control Statement
Control Statement
UNIT
6.3
PROGRAMMING LANGUAGE (JAVA)
Control Statements
OBJECTIVES
This unit enables you to understand the usage of appropriate branching and
looping statements in Java programs.
At the end of this unit, you will be able to
Benchmark Standard
Control Statements
6.3-1
Fundamentals of Programming
Let us Revise!
1. List the 8 basic primitive data types.
2. Define variables.
3. List any 5 keywords used in Java programs.
4. List the two types of typecasting.
5. Define operators.
Introduction
In our day-to-day life, we often need to take some decisions and perform
some actions based on the decisions taken. Watch the following statements:
In these statements, the decision of going for a walk, taking a diversion and
taking an umbrella depends on some condition being met. Similarly, in
programs we might need to take some decisions based on certain conditions.
In this unit, you will learn the use of control statements by which the
sequential flow of a program can be changed.
Control Statements
Java supports two types of control statements (refer to Figure 6.3.1). They are
used to alter the flow of the program.
Branching statements
Looping statements
Control Statements
6.3-2
Fundamentals of Programming
if
switch
Control Statements
6.3-3
Fundamentals of Programming
6.3-4
Fundamentals of Programming
The if statement will evaluate the condition. If the condition is satisfied or true,
the conditional statements are executed. If the condition is not satisfied or
false, the conditional statements are not executed.
The syntax for the if statement is:
if (<Condition>)
{
<Conditional statements>;
}
Body of the if
statement
Hands-On!
Control Statements
6.3-5
Fundamentals of Programming
Hands-On!
Control Statements
6.3-6
Fundamentals of Programming
6.3-7
Fundamentals of Programming
Hands-On!
Program
to illustrate the use of the if-else statement.
Program to explain the if-else branching statement
class Sample
{
public static void main (String args[])
{
int num;
This condition will check
num=Integer.parseInt(args[0]); whether the value of num
is less than 0.
if (num<0)
System.out.println("Negative");
else
This statement will be
System.out.println("Positive");
executed when num is
}
greater than 0.
}
Code Sample 6.3.3
If you run the program from the command line by typing java Sample 5 you will
get this output.
Output
Positive
Java programs can accept command line arguments from the user, when the
program is executed. In Code Sample 6.3.3, notice the line
num=Integer.parseInt(args[0]). When the program is executed, this line
accepts the integer value passed in the command prompt. The value is
passed as argument to the array args. args[0] is the first element of the args
array. The parseInt( ) method in Integer class is used to convert the user
input value(String) to integer. The value passed by the user in run time is
stored in the integer variable num.
Control Statements
6.3-8
Fundamentals of Programming
Lab Exercise
Lab Exercise 1: Accept two numbers from the keyboard and find the highest among them.
Lab Exercise 2: Accept a number from the keyboard and check whether it is divisible by 5.
Hint: Use the modulus operator, %, to check the divisibility.
Lab Exercise 3: Accept a number from the keyboard and check whether the number is an odd
or an even number.
Hint: Use the modulus operator, %, to check the divisibility.
Control Statements
6.3-9
Fundamentals of Programming
if (<Condition 1>)
{
if (<Condition 2>)
{
<Conditional statements1>;
}
else
{
<Conditional statements2>;
}
}
else
{
<Conditional statements3>;
}
Inner if
Condition
Outer if
Condition
You will notice that in this nested if, there are two if conditions, the inner if
condition and the outer if condition. The inner if condition is executed when
Condition 1 is satisfied. In the inner if, Condition 2 is checked. When Condition
1 is not satisfied, Conditional statements3 are executed.
Note
You can have any number of nested if statements within another if statement.
Control Statements
6.3-10
Fundamentals of Programming
Hands-On!
Program to illustrate the use of nested if statement.
class Highest
{
public static void main (String args[])
{
int x;
int y;
int z;
x = Integer.parseInt(args[0]);
y = Integer.parseInt(args[1]);
The condition checks whether
z = Integer.parseInt(args[2]);
the value in variable x is
greater than y.
if(x>y)
The condition checks whether
{
the value of x is greater than z.
if(x>z)
Prints the value of x and the text is the
highest if the condition is satisfied.
Output
8 is the highest
Control Statements
6.3-11
Fundamentals of Programming
The flowchart for the execution of Code Sample 6.3.4 is shown in Figure
6.3.5:
Control Statements
6.3-12
Fundamentals of Programming
Lab Exercise
Lab Exercise 4: Accept three numbers from the keyboard and find the greatest among them.
Lab Exercise 5: During a special sale at a mall, a 5% discount is given on purchases above
RM100.00. Write a program to accept the total purchase amount and calculate
the discounted price.
Example:
Enter the amount of purchase in RM: 2000
Discounted price = 2000-(2000*5/100) = 1900
Control Statements
6.3-13
Fundamentals of Programming
Hands-On!
Program to illustrate the switch case execution.
class SwitchDemo
{
The value of month
public static void main(String args[])
will be checked
{
against each case
and the statements
int month=Integer.parseInt(args[0]);
in the matching
switch (month)
case will be
executed.
{
case 1: System.out.println("January");
This case
break;
is executed
when the
case 2: System.out.println("February");
user enters
break;
the month
as 2.
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;
default: System.out.println("wrong choice");
}
This case is executed when
}
the value of month is not
equal to 1, 2, 3, 4, 5 or 6.
}
Code Sample 6.3.5
Control Statements
6.3-14
Fundamentals of Programming
If you run the program from the command line by typing java SwitchDemo
5 you will get this output.
Output
May
The following steps explain the execution of Code Sample 6.3.5:
1. The input given by the user in the command line is stored in the variable
month. Assume that you give the input as 5.
2. The program will then search whether a case is present for the given input.
3. When the corresponding case is found, the respective statements will be
executed. Here, since you entered 5, the case 5 will be executed. The text
May will be displayed.
When the control reaches the break statement, the rest of the cases will be
skipped and the control will be transferred outside the switch case.
4. When no match is found, the control will reach the default case and
execute the given statements.
Finally, the control is transferred outside the switch case.
Note
The break statement need not be included in the default case. After
executing the statements in the default case, the control automatically exits
the switch statement.
Hands-On!
Program to illustrate switch case (Character) execution.
//Program to check if the given character is a vowel.
class SampleSwitch
{
public static void main(String args[])
{
char ch = 'i';
switch (ch)
{
case 'a':
case 'A':
System.out.println("It is a vowel");
break;
Control Statements
6.3-15
Fundamentals of Programming
case 'e':
case 'E':
System.out.println("It is a vowel");
break;
When the input character is
case 'i':
either i or I, this case will be
executed.
case 'I':
System.out.println("It is a vowel");
break;
case 'o':
case 'O':
System.out.println("It is a vowel");
break;
case 'u':
case 'U':
System.out.println("It is a vowel");
break;
default:
System.out.println("It is not a vowel ");
}
}
}
Code Sample 6.3.6
Output
It is a vowel
The following steps explain the execution of Code Sample 6.3.6:
1. The value stored in variable ch is i.
2. The program will then search whether a case is present for the value in
variable ch.
3. When the corresponding case is found, the respective statements will be
executed. Here, as the character value is i, the case i and I will be
executed. The text It is a Vowel will be displayed.
When the control reaches the break statement, the rest of the cases will be
skipped and the control will be transferred outside the switch case.
4. When no match is found, the control will reach the default case and
execute the given statements.
5. Finally, the control is transferred outside the switch case.
Control Statements
6.3-16
Fundamentals of Programming
Lab Exercise
Lab Exercise 6: Write a program to accept the day of the week and print the day.
Example:
1 Sunday
5 Thursday
for
while
do-while
Control Statements
6.3-17
Fundamentals of Programming
These three parts of the for loop are separated by a semicolon. The flowchart
of for loop is shown in Figure 6.3.6.
Control Statements
6.3-18
Fundamentals of Programming
Control Statements
6.3-19
Fundamentals of Programming
Hands-On!
Program to illustrate the working of a for loop.
class LoopDemo
{
public static void main(String args[])
{
int value =3;
int num,multiple;
System.out.print("Multiples of 3: ");
for (num = 1; num <= 10; num++)
{
Each time, the loop control
variable num is incremented and
multiple=num*value;
multiplied with the value 3.
System.out.print(multiple+" ");
}
}
}
Code Sample 6.3.7
Output
Multiples of 3: 3 6 9 12 15 18 21 24 27 30
Warning
Do not terminate the for statement with a semicolon as it will end the for loop. If you
terminate the for statement, the statements within the curly brackets will no longer be a part of
the loop. The loop statements will be considered part of the program and will be executed just
once as other program statements.
Activity 6.3.2
Step 1: Open the data file LoopSample.java. The following Java statements will
be displayed on the screen:
1.
2.
3.
4.
5.
6.
class LoopSample
{
public static void main(String args[])
{
for(int j=0;j<5;j++)
{
Control Statements
6.3-20
Fundamentals of Programming
7.
8.
9.
10.
11.
Control Statements
6.3-21
Fundamentals of Programming
Series 2
1, 3, 5, 7n
Series 3
123
456
789
Control Statements
6.3-22
Fundamentals of Programming
int sum=0;
The value of i is initialised to 0.
int i=0;
Condition is checked.
while(i<=10)
{
This addition takes place till i is
less than or equal to 10.
sum=sum+i;
i++;
The value of i is incremented.
}
System.out.print("The total of first 10 numbers is:
"+sum);
Code Segment 6.3.2
Output
The total of first 10 numbers is: 55
The following steps explain the execution of Code Segment 6.3.2:
1. An integer variable sum to store the total is declared and initialised to 0.
2. The value of the loop control variable i is initialised to 0.
Control Statements
6.3-23
Fundamentals of Programming
3. The condition is checked. If the value of i is less than 10, the control
moves into the body of the while loop.
4. The value of i is added with the sum and stored.
5. The value of i is incremented.
6. Step 2, 3 and 4 are repeated as long as the condition is satisfied.
7. When the condition is not satisfied, the control moves out of the loop.
Hands-On!
Program to illustrate the working of a while loop.
class WhileDemo
{
public static void main(String args[])
{
int sum=0;
int i=0;
while(i<=10)
{
sum=sum+i;
i++;
}
System.out.println("Total : " +sum);
}
}
Code Sample 6.3.8
Output
Total : 55
Control Statements
6.3-24
Fundamentals of Programming
1.
class OddNo
2.
3.
4.
5.
int count;
6.
count = 1;
7.
while(count _____11)
8.
9.
10.
count=count+_______;
11.
12.
13.
}
}
Step 2: Fill in the blanks in line 7 and 10 such that the output of the program
is 1 3 5 7 9 11
Step 3: Save, compile and run the program to observe the output.
class SqNatNo
2.
3.
4.
5.
int square;
6.
int num;
7.
num = 1;
8.
while(num<= ___________)
9.
10.
square=___________;
11.
12.
Control Statements
num++;
6.3-25
Fundamentals of Programming
13.
14.
15.
}
}
Step 2: Fill in the blanks in code line 8 to complete the condition to repeat the
loop till it finds the square of first five natural numbers (1 to 5)
Step 3: Fill in the blanks in code line10 to find the square of the number.
Step 4: The output of the program should be as follows.
The square of 1 is: 1
The square of 2 is: 4
The square of 3 is: 9
The square of 4 is: 16
The square of 5 is: 25
Step 5: Save, compile and run the program to observe the output.
Activity 6.3.3 (c)
Step 1: Open the data file PostDecrement.java. The following Java statements
will be present.
1.
class PostDecrement
2.
3.
4.
5.
int count;
6.
count = 2;
7.
while(count>= ___________)
8.
9.
System.out.println(count);
10.
11.
12.
13.
}
}
Step 2: Fill in the blanks in code line 7 and 10 such that the output of the
program will be 2, 1, 0, -1.
Step 3: Save, compile and run the program to observe the output.
Control Statements
6.3-26
Fundamentals of Programming
Lab Exercise
Lab Exercise 10: Using a while loop generate the series
0, 1, 1, 2, 3, 5, 8
Control Statements
6.3-27
Fundamentals of Programming
Control Statements
6.3-28
Fundamentals of Programming
}while(x<15);
}
}
Code Sample 6.3.9
Output:
20
1. The loop control variable x is initialised to 20;
2. The control enters the loop and the value of x is displayed.
3. The value of x is then incremented by 1. Hence x becomes 21.
4. After executing the loop statements, the condition is checked. The
condition is not satisfied as the value of x is now 21.
5. The control passes out of the do-while loop.
In this do-while loop, you can notice that the value of x is displayed at least
once though the condition is not satisfied.
Activity 6.3.4(a)
Fill in the blanks with appropriate code.
Step 1: Open the data file Count_1.java. The following Java statements will be
present:
1.
class Count_1
2.
3.
4.
5.
int count=0;
6.
do
7.
8.
System.out.println(count+" ");
9.
________;
10.
}while (count<6);
11.
12.
}
}
Step 2: Fill in the blanks with appropriate code to increment the variable
count.
Step 3: Save, compile and execute the code.
Control Statements
6.3-29
Fundamentals of Programming
class Count_2
2.
3.
4.
5.
int count=6;
6.
do
7.
8.
System.out.println(count+" ");
9.
count++;
10.
}while (count<10);
11.
12.
}
}
Lab Exercise
Lab Exercise 11: Write a program that accepts an integer and print it backwards.
For example:
If the input is 53
Output: 35
Lab Exercise 12: Write a program that reads an integer and prints the sum.
For example:
If the input is 53
Output: 8
Control Statements
6.3-30
Fundamentals of Programming
Hands-On
Program to illustrate the use of break statement.
/* Program to illustrate the use of break statement */
class BreakDemo
{
public static void main(String args[])
{
int i;
System.out.println("Entering into the loop");
for(i=1;i<50;i++)
{
if(i==10)
break; // exit from for loop
System.out.print(i+" ");
}
System.out.println();
System.out.println("Exiting out of the loop");
}
}
Code Sample 6.3.10
Output
Entering into the loop
1 2 3 4 5 6 7 8 9
Exiting out of the loop
Control Statements
6.3-31
Fundamentals of Programming
Flowchart for the execution of Code Sample 6.3.10 is given in the Figure
6.3.9.
Control Statements
6.3-32
Fundamentals of Programming
Control Statements
6.3-33
Fundamentals of Programming
Control Statements
6.3-34
Fundamentals of Programming
Now the output will be Friday. Here, only the matching case statement
corresponding to the integer given as input is displayed. This is because the
break statement causes termination of the block of statements after the
matching case and transfers the control out of the switch construct.
Definition: The continue statement will transfer the control to the beginning
of the block of statements.
You can use the continue statement when you want the control to return to
the beginning of the loop without executing the rest of the statements in the
loop.
In a while or do-while, loop the continue statement passes the control to
the condition, skipping the loop statements following it. In a for loop, the loop
statements following continue are skipped. The control goes to the
incrementation/decrementation part (iteration) and then to the condition.
Hands-On!
Program to illustrate the use of continue statement.
class ContinueDemo
{
public static void main(String args[])
{
for(int i=1;i<=20;i++)
{
if(i%2!=0)
continue; //next iteration
System.out.print(i+" ");
}
}
}
Code Sample 6.3.13
Output
2 4 6 8 10 12 14 16 18 20
Flowchart for the execution of Code Sample 6.3.13 is given in the Figure
6.3.10.
Control Statements
6.3-35
Fundamentals of Programming
Control Statements
6.3-36
Fundamentals of Programming
Hands-On!
Program to print a series without a continue statement.
class ContinueDemo1
{
public static void main(String args[])
{
for(int i=1;i<=20;i++)
{
if(i%2!=0)
System.out.print(i+" ");
}
}
}
Code Sample 6.3.14
When there is no continue statement in the output will be as follows:
Output
1 3 5 7 9 11 13 15 17 19
Observe the difference in output in Code Sample 6.3.13 and Code Sample
6.3.14.
In case of Code Sample 6.3.13, when the condition is true the continue
statement in the if loop transfers the control to the beginning of for loop. The i
value is displayed only when the condition is false.
In case of Code Sample 6.3.14, when the condition is true, the value of i is
displayed, as there is no continue statement.
Technical Terminologies
Branching Statements
Control Statements
Looping Statements
Control Statements
6.3-37
Fundamentals of Programming
Summary
In this unit, you learnt that
Control statements are used for altering the normal flow of the
program.
The two types of control statements are branching statements and
looping statements.
Branching statements are used to evaluate expression and direct the
execution of the program, depending on the result of the evaluation.
The statements that are executed repeatedly are termed as looping
statements.
In Java, the branching statements include if and switch statements.
In Java, the looping statements include while, do-while and for
statements.
A single if statement is used to execute a set of statements when the
condition is satisfied.
It is possible to write if statements within the body of another if
statement to test multiple conditions. This type of if statement is
referred to as nested if.
The switch statement is used when you choose from a number of
choices.
The for loop is a looping statement that enables you to repeat a set of
instructions based on the condition. It is used when the number of
loops is known even before the first loop.
The while loop is a looping statement that enables you to repeat a set
of instructions based on the condition. It is used when the number of
loops is not known before the first loop.
The do-while loop is a looping statement that enables you to repeat a
set of instructions based on the condition.
The break statement will transfer the control to the statement outside
the loop.
The continue statement will transfer the control to the beginning of
the loop.
Assignment
1. Write short notes on control statements.
2. Write a program to accept three numbers and find the smallest
number.
3. Mention the looping statements available in Java.
Control Statements
6.3-38
Fundamentals of Programming
Please tick [
competency
Date
Control Statements
C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11
Comment
Date
C12
Control Statements
C13
C14
C15 C16
Comment
Competency codes:
C1 = Draw flowchart for the simple if programs.
C2 = Write programs using simple if statements.
C3 = Draw flowchart for the nested if programs.
C4 = Write programs using nested if statements.
C5 = Identify the structure of switch statement.
C6 = Write programs using switch statements.
Control Statements
6.3-39
Fundamentals of Programming
Control Statements
6.3-40