Sie sind auf Seite 1von 40

Fundamentals of Programming

Programming Language (JAVA)

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

Define branching statements


List the types of branching statements
Define looping statements
List the types of looping statements
Describe the structure and working of simple if statements
Describe the structure and working of nested if statements
Describe the structure and working of switch statements
Describe the structure and working of a for, while and do-while
loops
Explain the need for break and continue statements

Benchmark Standard

Perform conditional execution of statements using if and switch


statements.
Write programs quickly and efficiently using for loop statements,
while loop statements and do-while loop statements.

Control Statements

6.3-1

Fundamentals of Programming

Programming Language (JAVA)

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:

If the weather is fine, I will go for a walk.

If the road is jammed, I will take a diversion.

If it is raining, I will take an umbrella with me.

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

Programming Language (JAVA)

Figure 6.3.1: Types of Control Statements

Self-Check Exercise 6.3.1


1. What is the use of control statements?
2. List the types of control statements.
3. What are the types of branching statements and looping statements available in Java?

6.3.1 Single and Nested if Statement


Branching statements are used to evaluate expressions and direct the
execution of the program, depending on the result of the evaluation.
The branching statements supported by Java are:

if
switch

6.3.1 (A) Single if Statement


Definition: Single if statement is used to execute a set of statements when
the given condition is satisfied.
If you want to opt for higher studies after Form 5, look out for a college in
which you can apply for. On the other hand, if you want to go for work, then
look out for an organisation where you find a job. Figure 6.3.2 shows the
flowchart of the real life situation discussed.

Control Statements

6.3-3

Fundamentals of Programming

Programming Language (JAVA)

Figure 6.3.2: Flowchart to explain if statement


In programs, a set of statements can be executed based on the condition in
the if statement. The flowchart for the if statement execution is shown in
Figure 6.3.3.

Figure 6.3.3: Flowchart for if Statement


Control Statements

6.3-4

Fundamentals of Programming

Programming Language (JAVA)

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

As shown in the syntax, the keyword if is followed by a condition. The


condition is enclosed within a pair of brackets ( ). The conditional statements
are enclosed within the curly brackets { }.

Best Programming Practise


You need not use curly brackets when there is only one conditional statement.
r

Hands-On!

Program to illustrate the execution of a simple if statement.


/* Program to check whether the given number is greater
than 100 */
class InputValue
{
public static void main(String args[])
Accepts input from the command
{
line and stores it in the variable num.
int num;
num = Integer.parseInt(args[0]); This expression will check
whether the value of num is
if(num<100)
less than equal to 100.
{
System.out.println("Number is less than 100");
}
This statement will be
executed when the value
}
of num is less than 100.
}
Code Sample 6.3.1
If you run the program from the command line by typing java InputValue 50 you
will get this output.
Output
Number is less than 100

Control Statements

6.3-5

Fundamentals of Programming

Programming Language (JAVA)

The following steps explain the execution of Code Sample 6.3.1:


1. The program accepts the input from the command line from the user
and stores it in the variable num.
2. The program will then check whether the input value is less than 100.
3. If the input value is less than 100, the conditional expression will return
true.
4. The control will then be passed to the println statement inside the
branching statement. The text Number is less than 100 will be displayed.
5. If the input value is not less than 100, the conditional expression will
return false.
6. Hence the control will not pass inside the branching statement. It skips
the println statement which displays the text Number is less than 100.

Hands-On!

Program to illustrate the execution of a simple if statement based on two


conditions.
/* Program to check whether the marks is between 90 and
100 and to print the Grade */
class Marks
{
public static void main(String args[])
{
int marks;
This statement checks
marks = Integer.parseInt(args[0]);
whether the value of
marks is between 90
if ((marks>90) && (marks<100))
and 100.
System.out.println("Grade is A");
}
}
Code Sample 6.3.2
If you run the program from the command line by typing java Marks 95 you will
get this output.
Output
Grade is A
Code Sample 6.3.2, checks whether the value of marks lies between 90 and
100. Here, the following two conditions are checked:
1. Is marks is greater than 90.

Control Statements

6.3-6

Fundamentals of Programming

Programming Language (JAVA)

2. Is marks is less than 100.


The if statement is used for checking the condition. The println statement
is executed when the input value lies between 90 and 100.

6.3.1 (B) if-else Statement


The if-else statement is used to execute a set of statements based on the
condition. You might sometimes want a set of statements to be executed
when a condition is not satisfied. This cannot be done using a simple if
statement. You can use the if-else statement in such situations.
The flowchart for the if-else statement execution is shown in Figure 6.3.4:

Figure 6.3.4: Flowchart for if-else statement


The if-else statement will first check the condition. When the condition is
fulfilled, conditional statements1 will be executed. When the condition is not
fulfilled, conditional statements2 will be executed.
The syntax for the if-else statement is:
if (<condition>)
{
<Conditional statements1>;
}
else
{
<Conditional statements2>;
}
Control Statements

Executed when the


condition is satisfied.

Executed when the


condition is not
satisfied

6.3-7

Fundamentals of Programming

Programming Language (JAVA)

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.

Best Programming Practise


It is a good practise to indent the statements within the if statement to improve the readability
of programs.
The following steps explain the execution of Code Sample 6.3.3:
1. Initially, the program will accept a value and store it in the variable num.
2. When the control reaches the if statement, the program will check whether
the value of num is lesser than 0.

Control Statements

6.3-8

Fundamentals of Programming

Programming Language (JAVA)

3. If the condition is satisfied, the text Negative will be displayed.


4. If the condition is not satisfied, the text Positive will be displayed.
Note
You need not use curly brackets when there is only one statement to be executed when the if
or else condition is satisfied.
Activity 6.3.1

Step 1: Open the data file InpSample.java.


1.
class InpSample
2.
{
3.
public static void main(String args[])
4.
{
5.
int num=14;
6.
if(num<20)
7.
System.out.println("Number is less than 20");
8.
else
9.
System.out.println("Number is greater than 20");
10.
}
11. }
Step 2: Run and observe the output.
Step 3: Draw the appropriate flowchart for the program.

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.

6.3.1 (C) Nested if Statement


You can 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 syntax for nested if statement is:

Control Statements

6.3-9

Fundamentals of Programming

Programming Language (JAVA)

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

Programming Language (JAVA)

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.

System.out.println(x + " is the highest");


else
System.out.println(z + " is the highest");
}
else
Checks whether the value of y is
{
greater than z.
if (y>z)
System.out.println(y + " is the highest");
else
System.out.println(z +" is the highest");
}
}
}
Code Sample 6.3.4
If you run the program from the command line by typing java Highest 8 2 4
you will get this output.

Output
8 is the highest

Control Statements

6.3-11

Fundamentals of Programming

Programming Language (JAVA)

The flowchart for the execution of Code Sample 6.3.4 is shown in Figure
6.3.5:

Figure 6.3.5: Flowchart for Nested if statement


The following steps explain the execution of Code Sample 6.3.4:
1. The program will first accept the values of x, y and z from the
command prompt, when you execute the program using java highest 8
2 4, for example.
2. When the control reaches the outer if condition, the program will check
whether the value of x is greater than y.
3. If x is greater than y, the condition is satisfied. The control moves to the
next if statement within it. The condition checks whether the value of x
is greater than the value of z.

Control Statements

6.3-12

Fundamentals of Programming

Programming Language (JAVA)

4. If x is greater than z, the condition is satisfied. The program will display


the value of x along with the text is the biggest. The control will then exit
the program.
5. If the condition is not satisfied, the program will display the value of y
along with the text is the highest. The control will then exit the program.
6. If the outer if condition is not satisfied, the program will check whether
the value of y is greater than the value of z.
7. If y is greater than z, the condition is satisfied and the program will
display the value of y along with the text is the highest.
8. If y is not greater than z, the condition is not satisfied and the program
will display the value of z along with the is the highest.

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

6.3.2 switch Statement


Definition: A switch statement is a multiway branching statement. In this
type of branching statement, the case statements are executed based on the
value of the expression.
The syntax for switch statement is:
switch (<expression>)
{
case <constant1>:
<Statements1>;
break;
case <constant2>:
<Statements2>;
break;
...
...
default:
<Statementsn>;
}

Control Statements

6.3-13

Fundamentals of Programming

Programming Language (JAVA)

The expression following the keyword switch can either be an integer


expression or a character expression. A switch statement has a number of
case statements inside the branch. An integer or a character constant follows
the keyword case. Based on the value returned from the expression in the
switch, the control is passed to the respective matching case.
The keyword break must be included in each case. A break statement
passes the control outside switch structure. In the absence of a break
statement, all the other case statements following the matching case will also
be executed. Hence, it is important to include a break statement to skip the
cases following the matching case.
In the syntax, notice the keyword default: present along with a set of
statements. When a matching case is found for the value of the switch
expression, the statements following that case will be executed. When there is
no matching case, the statements in the default case will be executed.

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

Programming Language (JAVA)

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

Programming Language (JAVA)

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

Programming Language (JAVA)

Lab Exercise
Lab Exercise 6: Write a program to accept the day of the week and print the day.
Example:
1 Sunday
5 Thursday

6.3.3 for, while and dowhile Statements


Definition: Looping statements are used to execute a set of instructions
repeatedly, as long as the specific condition is satisfied.
The looping statements available in Java are:

for
while
do-while

Self-Check Exercise 6.3.2


Answer the following questions:
1. What is looping statements?
2. List the looping statements supported by Java.

6.3.3 (A) for Loop


Definition: 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 before the first loop.
The for loop is a well-formatted loop. The number of loops or the number of
times the statements are to be executed should be known even before the
first loop. The for loop is the most commonly used looping structure. The
syntax for the for loop is:
for(initialisation;condition;incrementation/
decrementation)
{
//loop statements
}
The for loop has three parts:

Initialisation: The initial value of the loop control variable is set


here.

Control Statements

6.3-17

Fundamentals of Programming

Programming Language (JAVA)

Condition: The loop condition is specified and the loop statements


are executed as long as this condition is satisfied.
Incrementation / Decrementation: The initial value of the loop
control variable is either incremented or decremented each time the
loop gets executed.

These three parts of the for loop are separated by a semicolon. The flowchart
of for loop is shown in Figure 6.3.6.

Figure 6.3.6: Flowchart to Explain the Working of a for Loop


Step 1: The first step in the for loop execution is to initialise or set value for
the loop control variable. This is done in the initialisation part. The
initialisation part is executed only once.
Step 2: Next step is to check whether the condition is satisfied.
Step 3: The control passes to the statements inside the loop and the
statements are executed.
Step 4: The value of the loop control variable is then incremented or
decremented based on the expression in this portion.
Step 5: The condition is checked again and the steps 3 and 4 are repeated till
the condition becomes false. When the condition becomes false the
control comes out of the for loop.

Control Statements

6.3-18

Fundamentals of Programming

Programming Language (JAVA)

Consider the example given in Code Segment 6.3.1:


Initialise the loop control variable count
to 1.
Checks the condition whether the
value of count is less than equal to 5.

for (count = 1; count <= 5; count++)


{
System.out.print(count+" ");
Increments the value of count by 1.
}
Statement displayed till the value
of count is less than or equal to 5.

Code Segment 6.3.1


Output
1 2 3 4 5
In Code Segment 6.3.1, count is the loop control variable. count<=5 is the
condition and count++ is the increment counter. The following steps explain
the execution of Code Segment 6.3.1:
1. When the control enters the loop for the first time, the value of count is
initialised to 1.
2. Next, the condition is checked. If the value of count is less than or equal to
5, the control is passed to the body of the loop.
3. The body of the loop is executed. Here, the value of count is displayed on
the screen.
4. When the control reaches the closing brackets of the loop, the value of
count is incremented by 1.
5. Step 2, 3 and 4 are repeated as long as the test condition is satisfied.
6. When the test condition is not satisfied, the control comes out of the for
loop and the rest of the program statements are executed.
When you observe the output, you will notice that the loop in Code Segment
6.3.1 was executed 5 times.

Best Programming Practise

Always indent the statements within the for loop.


You can omit the curly brackets if there is only one statement within the body of
the for loop.

Control Statements

6.3-19

Fundamentals of Programming

Programming Language (JAVA)

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.

Programming Language (JAVA)

System.out.print(j + " ");


}
System.out.println();
System.out.println("Outside the for loop");
}
}

Step 2: Run and observe the output.


Step 3: Draw a flowchart for the above program
Lab Exercise
Lab Exercise 7: Write a program to print the following triangle of numbers:
1
12
123
1234
12345
Lab Exercise 8: Write a program that will accept a number from the user and print the
multiplication table for that number in the proper format.
Example: If the input is 2, print the 2 tables in the following format:
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
Lab Exercise 9: Display the following series using for loop.
Series 1
1
12
123
1234

Control Statements

6.3-21

Fundamentals of Programming

Programming Language (JAVA)

Series 2
1, 3, 5, 7n
Series 3
123
456
789

6.3.3 (B) while Loop


Definition: The while loop is a looping statement that enables you to repeat
a set of instructions based on a condition. It is used when the number of loops
is not known before the first loop.
The while loop is similar to the for loop and is used to perform certain tasks
repeatedly. Use the while loop when the number of loops is not known before
the first loop.
Syntax
<Initialise variable>;
while(condition)
{
//loop statements
<Increment/decrement variable>;
}

As shown in the syntax, the keyword while is followed by a conditional


expression. The condition is enclosed within a pair of brackets ( ). The while
statement is followed by a pair of curly brackets { } within which the loop
statements, that are to be executed, are written. You will notice that the loop
control variable is initialised before the while statement. The value of the loop
control variable is incremented or decremented within the body of the loop.
Figure 6.3.7 represents the flowchart for the while loop.

Control Statements

6.3-22

Fundamentals of Programming

Programming Language (JAVA)

Figure 6.3.7: Flowchart for while Loop


In a while loop, the condition is initially checked or evaluated. Based on the
evaluation results, the statements below the while statement are executed.
Code Segment 6.3.2 shows how a while loop can be used to find the sum of
numbers from 1 to 10.

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

Programming Language (JAVA)

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.

Best Programming Practise

Always indent the statements within a while loop.


The curly brackets can be avoided if there is only one statement within the body of
the while 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

Activity 6.3.3 (a)


Step 1: Open the data file OddNo.java. The following Java statements will be
present:

Control Statements

6.3-24

Fundamentals of Programming

1.

class OddNo

2.

Programming Language (JAVA)

3.

public static void main(String args[])

4.

5.

int count;

6.

count = 1;

7.

while(count _____11)

8.

9.

System.out.println(count + " ");

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.

Activity 6.3.3 (b)


Step 1: Open the data file SqNatNo.java. The following Java statements will be
displayed on the screen.
1.

class SqNatNo

2.

3.

public static void main(String args[])

4.

5.

int square;

6.

int num;

7.

num = 1;

8.

while(num<= ___________)

9.

10.

square=___________;

11.

System.out.println("The square of "+ num +


" is: "+square);

12.

Control Statements

num++;

6.3-25

Fundamentals of Programming

13.

14.
15.

Programming Language (JAVA)

}
}

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.

public static void main(String args[])

4.

5.

int count;

6.

count = 2;

7.

while(count>= ___________)

8.

9.

System.out.println(count);

10.

count = count - ___________;

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

Programming Language (JAVA)

Lab Exercise
Lab Exercise 10: Using a while loop generate the series
0, 1, 1, 2, 3, 5, 8

6.3.3 (C) do-while Loop


Definition: The do-while loop is a looping statement that enables you to
repeat a set of instructions based on the condition. In a do-while loop, the
body of the loop of executed at least once before the condition is checked.
The do-while loop is similar to the while loop, with the difference only in the
location where the condition is checked, as shown in Figure 6.3.8.
Syntax
do
{
//loop statements
} while(condition );
In a do-while loop, the do keyword is followed by the loop statements within
the curly brackets. The condition is checked at the end of the execution of the
loop statements.
You have learnt that in case of a while loop, the condition is checked first and
only if it is true, the loop statements are executed. Sometimes, there may be a
need to execute the loop statements once, even if the condition is false. In
this case, you can use the do-while loop. The flowchart for do-while loop is
shown in Figure 6.3.8.

Control Statements

6.3-27

Fundamentals of Programming

Programming Language (JAVA)

Figure 6.3.8: Flowchart for do-while Loop


In the flowchart, notice that the condition is checked after the execution of the
loop statements.
Each time, the loop statements are executed and then the condition is
checked. If the condition is satisfied, the loop will repeat for the next time.
Note
The do-while loop must be terminated with a semicolon.
Hands-On!
Program to illustrate the working of a do-while loop.
class DoWhileDemo
{
public static void main(String args[])
{
int x=20;
do
{
System.out.print(x);
x=x+1;

Control Statements

6.3-28

Fundamentals of Programming

Programming Language (JAVA)

}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.

public static void main(String args[])

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

Programming Language (JAVA)

Activity 6.3.4 (b)


Write the output for the program.
Step 1: Open the data file Count_2.java. The following Java statements will be
present:
1.

class Count_2

2.

3.

public static void main(String args[])

4.

5.

int count=6;

6.

do

7.

8.

System.out.println(count+" ");

9.

count++;

10.

}while (count<10);

11.
12.

}
}

Step 2: Read the program and write the output.

Self-Check Exercise 6.3.3


Answer the following questions:
1. When will you use a while loop?
2. What is the difference between a while loop and a do-while loop?

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

Programming Language (JAVA)

6.3.3 (D) break and continue Statement


The break and continue statements in Java allow transfer of control from
one statement to another.
Definition: The break statement causes termination of the block of
statements within the curly brackets and transfers the control outside the loop
or block.
During execution, when the keyword break is encountered within a loop, the
control is immediately transferred to the statement outside the loop.

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

Programming Language (JAVA)

Flowchart for the execution of Code Sample 6.3.10 is given in the Figure
6.3.9.

Figure 6.3.9: Flowchart for break Statement


1. In the program, the for loop is given in which i is initialised to 1.
2. Then, the condition if i is less than 50 is checked.
3. As i is less than 50, the control enters the loop and checks if i is equal to
10. The condition is not satisfied. So the control flows without break.
4. The value of i is displayed.
5. Then, the value of i is incremented by 1 and the steps 4 and 5 are
repeated till i value is 9.
6. When the value of i becomes 10, the break statement skips the loop
statement to display the value of i. The control passes outside the loop.

Control Statements

6.3-32

Fundamentals of Programming

Programming Language (JAVA)

Consider the following example without a break statement:


class demoSwitch
{
public static void main(String args[])
{
int num;
num=Integer.parseInt(args[0]);
switch(num)
{
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
case 4:
System.out.println("Thursday");
case 5:
System.out.println("Friday");
case 6:
System.out.println("Saturday");
case 7:
System.out.println("Sunday");
}
}
}
Code Sample 6.3.11
Just execute the program entering java demoSwitch 5, the output will be as
follows:
Output
Friday
Saturday
Sunday

Control Statements

6.3-33

Fundamentals of Programming

Programming Language (JAVA)

Consider the following example with a break statement:


class demoSwitch
{
public static void main(String args[])
{
int num;
num=Integer.parseInt(args[0]);
switch(num)
{
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;
}
}
}
Code Sample 6.3.12
Just execute the program entering java demoSwitch 5, the output will be as
follows:
Output
Friday

Control Statements

6.3-34

Fundamentals of Programming

Programming Language (JAVA)

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

Programming Language (JAVA)

Figure 6.3.10: Flowchart for continue Statement


1. In the for loop in the program, i is first initialised to 1.
2. The program then checks whether i is less than 20.
3. As i is less than 20, the control enters the loop.
4. The program then checks the whether the remainder of i divided by 2 is
not equal to 0.
5. When the remainder is not equal to zero, the continue statement
passes the control to the beginning of for loop.
6. The value of i is incremented to 2.
7. The steps 2, 3 and 4 are repeated.
8. Now, as the remainder of i divided by 2 is equal to 0, the continue
statement is skipped. The value of i is displayed.
9. The value of i is again incremented and the steps 2,3 and 4 are
repeated.

Control Statements

6.3-36

Fundamentals of Programming

Programming Language (JAVA)

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

Branching statements are used to evaluate


expression and direct the execution of the
program, depending on the result of the
evaluation.

Control Statements

Looping Statements

Control Statements are used for altering the


normal flow of the program.
These statements that are used for executing a
set of statements repeatedly based on the
condition.

Control Statements

6.3-37

Fundamentals of Programming

Programming Language (JAVA)

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

Programming Language (JAVA)

Criterion Referenced Test


Instruction: Students must evaluate themselves to attain the list of
competencies to be achieved
Name:
Subject: Programming Language (JAVA)
Unit : Control Statements

Please tick [
competency
Date

] the appropriate box when you have achieved the respective

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

Programming Language (JAVA)

C7 = List the types of looping statements.


C8 = Draw flowchart for the for loop.
C9 = Write program using for loop.
C10 = Identify the structure of the while loop.
C11 = Draw flowchart for the while loop.
C12 = Write program using while loop.
C13 = Identify the structure of the do-while loop.
C14 = Draw flowchart for the do-while loop.
C15 = Write program using do-while loop.
C16 = Use any of two statements (break, continue) to transfer the control
out of the loop.

Control Statements

6.3-40

Das könnte Ihnen auch gefallen