Control Flow Statements
Control Flow Statements
DATE : 17.09.2024
Contents
• Introduction
• Branching - Conditional
• Looping
• Nested Loop
• Branching – Unconditional
• Quiz
Introduction
• Control flow is the order in which individual statements or instructions of a program are executed or
evaluated and Control flow statements is categorized as follows:
Control Statements
for
Conditional Unconditional while
Statements Statements
Simple If do..while
break
If..else If..elseif..else
continue
Switch
case Nested if
5 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Introduction
• Sequential statements describe a sequence of actions that a program carries out one after another,
unconditionally.
Example:
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
double area = Math.PI * radius * radius;
System.out.println("The area of the circle with radius " + radius + " is: " + area);
scanner.close();
}
}
Introduction
• if
• if…else
• if-else-if
• nested if
• switch
Decision-Making : simple if
• Simple if: If the condition is true, the body of the if statement is executed. If it is false, the body
if ( condition ){
statement(s);
}
Decision-Making : simple if
/** Output:
* The IfControlStructure class implements an application that
10
* Illustrate the if decision Making control statement
*/
class IfControlStructure{
public static void main(String[] args){
boolean isMoving=true;
int currentSpeed=10;
if(isMoving){
System.out.println(currentSpeed);
}
}
}
Decision-Making : simple if
/**
*The SimpleIf class implements an application that checks the seat availability status for movie ticket booking using
*simple if decision Making control statement
*/
import java.util.Scanner;
public class SimpleIf {
public static void main(String[] args){
boolean seatAvailable = true; //Seat Available Status
Scanner input = new Scanner(System.in); //Scanner class object creation
System.out.println("Enter the Seat Number : ");
String SeatNumber = input.next(); //get Seat Number from User
Decision-Making : simple if
Output:
Enter the Seat Number : A32
Your have booked the seat number : A32
• if –else: If the condition is true, the body of the if statement is executed. If it is false, the body of
• Syntax
if ( condition ){
if Body;
}
else{
else Body;
}
/** * The SimpleIfElse class implements an application that that checks the seat availability status for movie ticket
booking using the if ..else decision-Making control statement */
Output:
Enter the Seat Number : A22
Seat Numer A22 is already booked
• if-else-if: It is also called else-if ladder. Here execute any one block of statements among many blocks.
• Syntax
if ( condition 1){
statement 1;
}else if ( condition 2 ){
statement 2;
}else if (condition 3){
statement 3;
} else {
else Body
}
/** Output:
* The IfEsleIFControlStructure class implements an application that
Color Red!
* Illustrate the if ..elseif decision Making control statement */
class IfElseIFControlStructure{
public static void main(String[] args){
int colorValue=2;
if(colorValue==1)
System.out.println(“Color Blue!”);
else if(colorValue==2)
System.out.println(“Color Red!”);
else
System.out.println(“Color Green!”);
}
}
Output:
Type of seats Available
REGULAR
PREMIUM
EXECUTIVE
VIP
choose any one of the option : PREMIUM
You have selected Premium Seat and cost Rs.100
Decision-Making : Nested if
• Nested if: Use more than if statement inside another if statement. The outer if statement condition true
means inside if statements execute.
• Syntax
if ( condition 1){
if ( condition 2 ){
Nested if Body
}else{
Nested else Body
}
}else
else Body
}
21 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Decision-Making : Nested if
Decision-Making : Nested if
/* * The Booking class implements an application that validates the login and check for the seat availability
* using nestedif decision Making control statement */
import java.util.*;
public class NestedIf {
public static void main(String[] args){
String username = "Sarvesh",password = "sarvesh@123",usernameentered,passwordentered;
boolean seatAvailable = true;
String seatNumber;
Scanner input = new Scanner(System.in); //Scanner class object creation
System.out.println("Enter the Username : ");
username = input.next(); //getting the username
System.out.println("Enter the Password : ");
password = input.next(); //getting the username
23 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Decision-Making : Nested if
Decision-Making : Nested if
Output:
Enter the Username : Sarvesh
Enter the Password : sarvesh@123
You have logged in and you can book a ticket now
Enter the Seat Number : A10
Seat Number A10 you have chosen is available
• switch-case: Select one of many possible statements to execute. It gives alternate for
long if..else..if ladders which improves code readable.
• Syntax
switch ( expression ) {
case value1 :
statement-list1;
break;
case value2 :
statement-list 2;
break;
default:
statement-list 3;
break;
}
26 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Note:
• In switch, Case value must be in expression type only and case values must be unique.
• Each case break statement is optional. It helps terminate from switch expression. If a break
default:
System.out.println("Invalid Letter");
break;
}
}
Output:
Uppercase Letter
/** The SwitchCase class implements an application that demonstrate the movie searching by different types of languages
* using switch decision Making control statement Searching the Movie detail by Title, Language, ReleaseDate, Genre*/
import java.util.Scanner;
public class SwitchCase {
public static void main(String[] args){
System.out.println("Enter the type to be search \n1. Search by Title \n2. Search by Language \n3. Search by Release
Date \n4. Search by Genre \nEnter the Choice (1/2/3/4)");
Scanner input = new Scanner(System.in); //Scanner class object creation
int choice = input.nextInt(); //getting the choice from user
switch(choice){
case 1:
System.out.println("Your searching choice is Movies by Title");
break;
case 2:
30 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Output:
Enter the type to be search
1. Search by Title
2. Search by Language
3. Search by Release Date
4. Search by Genre
2
Your searching choice is Movies by Languagec
Looping - Introduction
• Loop/ iterative statements are used for executing a block of statements repeatedly until a particular
condition is satisfied.
• while
• do…while
• for
• for…each
Looping - Introduction
• Initialization: To set initial value to the iteration variable at the very start of the loop.
• Loop-body: If the test condition is true, the body of the loop runs once.
• Updation: Increment/decrement statement executes just after executing the body, and then the
Looping - while
• while: It is used to rrepeat a specific block of code. It is preferable while we do not know the exact
• Syntax
while (condition){
statement(s)
}
Looping - while
/**
* The WhileStructure class implements an application that
* Illustrate While Looping control statement
*/
class WhileStructure{
public static void main(String[] args){
int counter = 1;
while (counter < 11)
{
System.out.println("Count is: " + counter);
counter++;
}
}
}
Looping - while
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Looping - while
/**
* The ShowSeat class implements an application that display the current seat availability
* using While Looping control statement
*/
public class ShowSeat {
public static void main (String args[]){
int MaxSeatCount = 10, seatCount = 0;
while(seatCount < MaxSeatCount){
System.out.println(“Current Seat Availability : "+(MaxSeatCount-seatCount));
seatCount++;
}
System.out.println("Seats are Filled");
}
}
38 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Looping - while
Output:
Current Seat Availability : 10
Current Seat Availability : 9
Current Seat Availability : 8
Current Seat Availability : 7
Current Seat Availability : 6
Current Seat Availability : 5
Current Seat Availability : 4
Current Seat Availability : 3
Current Seat Availability : 2
Current Seat Availability : 1
Seats are Filled
Looping - do - while
• do-while: Executes the statement first and then checks for the condition. It is also called an
exit-controlled loop.
• Syntax
do {
statement(s)
} while (condition);
Looping - do - while
/**
* The DoWhileStructure class implements an application that that checks the seat availability
* status for movie ticket booking and Illustrate do..while Looping control statement
*/
class DoWhileStructure{
public static void main(String[] args){
int counter = 1;
do {
System.out.println("Count is: " + counter);
counter++;
} while (counter < 11)
}
}
Looping - do - while
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Looping - do - while
/**
* The ShowSeat class implements an application that that checks the seat
* availability status for movie ticket booking using do.. while Looping control statement */
public class ShowSeat {
public static void main (String args[]){
int MaxSeatCount = 5, seatCount = 0;
do{
System.out.println("Current Seat Availability : "+(MaxSeatCount-seatCount));
seatCount++;
} while(seatCount < MaxSeatCount);
System.out.println("Seats are Filled");
}
}
Looping - do - while
Output:
Current Seat Availability : 5
Current Seat Availability : 4
Current Seat Availability : 3
Current Seat Availability : 2
Current Seat Availability : 1
Seats are Filled
Looping - for
• for: When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop
• Syntax
for (initialization; condition ; updation) {
statement(s)
}
Looping - for
/**
*/
class ForStructure{
Looping - for
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Looping - for
/**
* The ShowSeat class implements an application that that checks the seat availability status for
*/
class ShowSeat{
public static void main (String args[]){
int MaxSeatCount = 5, seatCount = 0;
for(seatCount=0;seatCount < MaxSeatCount;seatCount++){
System.out.println("Current Seat Availability : "+(MaxSeatCount-seatCount));
}
System.out.println("Seats are Filled");
}
}
48 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Looping - for
Output:
Current Seat Availability : 5
Current Seat Availability : 4
Current Seat Availability : 3
Current Seat Availability : 2
Current Seat Availability : 1
Seats are Filled
• for-each: It’s commonly used to iterate over an array or a Collections class. It is also called
• Syntax:
for (type var : arrayName) {
statements;
}
• It is used to iterate over the elements of a collection without knowing the index of each element.
• It is immutable which means the values which are retrieved during the execution of the loop are read
only
/**
* The ForEachApp class implements an application that
* illustrate foreach looping Structure
*/
class ForEachApp{
public static void main (String args[]){
int[] marks = { 125, 132, 95, 116, 110 };
int maxSoFar = marks[0];
//for each loop
Output:
The highest score is 132
/**
* The ForEach class implements an application that list the movie based on their Genre
* using foreach looping Structure
*/
import java.util.Scanner;
public class ForEach {
public static void main(String[] args) {
String MovieName[] = {"AAA","BBB","CCC","DDD"};
String MovieGenre[] = {"ACTION","COMEDY","THRILLER","ACTION"};
Scanner input = new Scanner(System.in); //Scanner class object creation
System.out.println("Enter the Genre to be searched : ");
String Genre = input.next();
int counter = 0;
53 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Nested Loop
• Nested Loop: A loop inside another loop is called a nested loop. The number of loops depend on the
requirement of a problem. It contains outer loop and inner loop. For each iteration of outer loop the inner
• Syntax
while(condition) {
for (initialization; condition; updation) { do { ……….
statements(s)
…….. statement(s)
while(condition) {
for (initialization; condition; updation) { do {
statement(s) statement(s)
statement(s)
……. ………
……..
} } while(condition);
}
………. ……….
………..
} } while(condition);
}
Nested Loop
/**
* The NestedWhileApp class implements an application that
* illustrate nested while loop */
class NestedWhileAPP{
public static void main (String args[]){
int outerLoop=1,innerLoop=1;
whlie(outerLoop<=5){
while(innerLoop<=5){
System.out.print(“*”);
innerLoop++;
}
Nested Loop
System.out.println(“ “);
outerLoop++;
innerLoop=1;
}
}
}
Output:
*****
*****
*****
*****
*****
Nested Loop
/**
* The NestedWhile class implements an application that demonstrate the seat availability while the seats are getting
booked in multiple screens using nested while loop */
class NestedWhile{
public static void main (String args[]){
int MaxSeatCount = 5, TotalScreenCount = 2, seatCount = 0, screenCount = 0;
while(screenCount < TotalScreenCount){
seatCount = 0;
System.out.println("Screen "+(screenCount+1)+" Availability details");
while(seatCount < MaxSeatCount){
System.out.println("Current Seat Availability : "+(MaxSeatCount-seatCount));
seatCount++;
}
58 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Nested Loop
Nested Loop
/** Output:
* The Nested DoWhileApp class implements an application that illustrate nested do…while loop */
class NestedDoWhileApp {
111222333
public static void main (String args[]){
int outerLabel= 1;
do {
int innerLabel = 1;
do{
System.out.print(outerLabel);
innerLabel++;
Nested Loop
/**
* The NestedDoWhile class implements an application that demonstrate the seat availability while the seats are
getting booked in multiple screens using nested do…while loop */
class NestedDoWhile{
public static void main (String args[]){
int MaxSeatCount = 10, TotalScreenCount = 2, seatCount = 0, screenCount = 0;
do{
System.out.println("Screen "+(screenCount+1)+" Availability details");
seatCount = 0;
do{
System.out.println(“Current Seats Availability : "+(MaxSeatCount-seatCount));
seatCount++;
} while(seatCount < MaxSeatCount);
61 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Nested Loop
Nested Loop
/**
* The Nested ForApp class implements an application that
* illustrate nested for looping structure
*/
class NestedForApp
{
public static void main (String args[])
{
int rows = 5;
// outer loop
Nested Loop
Nested Loop
/**
* The NestedFor class implements an application that demonstrate the seat availability while the seats are getting
booked in multiple screens and illustrate nested for looping structure
*/
class NestedFor{
Nested Loop
} Output:
Screen 1 Availability details
System.out.println("Seats Filled in Screen "+(screenCount+1));
Current Seat Availability : 5
}
Current Seat Availability : 4
}
Current Seat Availability : 3
} Current Seat Availability : 2
Current Seat Availability : 1
Seats Filled in Screen 1
Screen 2 Availability details
Current Seat Availability : 5
Current Seat Availability : 4
Current Seat Availability : 3
Current Seat Availability : 2
Current Seat Availability : 1
Seats Filled in Screen 2
66 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Branching - Unconditional
• Branching (Unconditional) - To transfers the control from one part of the program to another part
• break
• labelled break
• continue
• labelled continue
Branching - Unconditional
• break: When a break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop.
• The Java break is used to break loop or switch statement. It breaks the current flow of the program
• Break statement use all types of loops such as for loop, while loop and do-while loop.
• Syntax
break;
Branching - Unconditional
/** Output:
Branching - Unconditional
/**
* The UnconditionalBreak class implements an application that demonstrate the seat availability while the seats are
getting booked assuming that the VIP seats are already reserved using Break branching statement
*/
class UnconditionalBreak {
public static void main (String args[]){
int premiumSeat = 5, vipSeat = 5, seatBooked = 0;
int totalSeat = premiumSeat + vipSeat;
for(seatBooked = 0;seatBooked < totalSeat;seatBooked++) {
if(seatBooked > premiumSeat) {
Branching - Unconditional
else {
System.out.println(“PREMIUM Seat Availability : "+(premiumSeat - seatBooked));
}
}
}
}
Branching - Unconditional
Output:
PREMIUM Seat Availability : 5
PREMIUM Seat Availability : 4
PREMIUM Seat Availability : 3
PREMIUM Seat Availability : 2
PREMIUM Seat Availability : 1
All PREMIUM Seats Booked
All VIP Seats 6 to 10 are Reserved
Branching - Unconditional
• continue: When you need to jump to the next iteration of the loop immediately.
• It continues the current flow of the program and skips the remaining code at the specified condition.
• Continue statement use all types of loops such as for loop, while loop and do-while loop.
• Syntax:
continue;
Branching - Unconditional
/** Output:
* The ContinueApp class implements an application that Count is: 1
* illustrate Continue branching statement Count is: 2
*/ Count is: 3
class ContinueApp { Count is: 4
Count is: 6
public static void main (String args[]) {
Count is: 7
for(int count = 1;count<10;count++) {
Count is: 8
if(count ==5) Count is: 9
continue;
System.out.println("Count is: " + count);
}
}
Branching - Unconditional
/**
* The UnconditionalContinue class implements an application that demonstrate the seat availability while the seats are
getting booked assuming that the VIP seats are already reserved using Continue branching statement
*/
class UnconditionalContinue {
Public static void main (String args[]){
int executiveSeat = 5, premiumSeat = 5, vipSeat = 5, seatBooked = 0;
int totalSeat = regularSeat + executiveSeat + premiumSeat + vipSeat;
for(seatBooked = 0;seatBooked < totalSeat;seatBooked++) {
if(seatBooked < (vipSeat)){
System.out.println("All VIP Seats 1 to 5 are Reserved ");
continue;
}
Branching - Unconditional
Branching - Unconditional
• Labeled Loop: In java, use labels with break and continue. A Label is used to identify a block of code.
In case of multiple loop involved use labeled loop to transfer any specific loop with help of labels.
Branching - Unconditional
/** * The LabeledBreakApp class implements an application that * illustrate Labeled Break */
Output:
class LabeledBreakApp{
00
public static void main(String args[]){
01
first: // First label 02
for (int i = 0; i < 3; i++) { 10
second: // Second label
for (int j = 0; j < 3; j++) {
if (1== i && 1 == j) {
// Using break statement with label
break first;
}
System.out.println(i + " " + j);
}
}
}
}
78 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Branching - Unconditional
/** * The LabeledBreakApp class implements an application that illustrate Labeled Break */
public class LabelledBreak {
public static void main (String args[]){
int MaxSeatCount = 10, TotalScreenCount = 2, seatCount = 0, screenCount = -1;
Start:
//System.out.println(screenCount);
while(screenCount < TotalScreenCount){
screenCount++;
System.out.println("Screen "+(screenCount+1)+" Seat Booked detail");
seatCount=0;
while(seatCount < MaxSeatCount){
if(seatCount >3 && screenCount == 1) {
System.out.println("Seat No 4 & 5 are Reserved");
Branching - Unconditional
break Start;
}
else
System.out.println("Seats No Booked : "+(seatCount+1));
seatCount++;
}
System.out.println("All Seats Filled in Screen "+(screenCount+1));
}
}
}
Branching - Unconditional
Output:
Screen 1 Seat Booked detail
Seats No Booked : 1
Seats No Booked : 2
Seats No Booked : 3
Seats No Booked : 4
Seats No Booked : 5
All Seats Filled in Screen 1
Screen 2 Seat Booked detail
Seats No Booked : 1
Seats No Booked : 2
Seats No Booked : 3
Seat No 4 & 5 are Reserved
81 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Branching - Unconditional
/*** The LabeledContinueApp class implements an application that illustrate LabeledContinue loop */
Output:
class LabeledContinueApp {
00
public static void main(String args[]){ 01
first: // First label 02
for (int i = 0 ; i < 3; i++) { 10
second: // Second label 20
for (int j = 0; j < 3; j++) { 21
if (1 == i && 1 == j) { 22
// Using continue statement with label
continue second;
}
System.out.println(i + " " + j);
}
}
}
}
82 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Branching - Unconditional
/*** The LabeledContinueApp class implements an application that illustrate LabelledContinue loop */
public class LabelledContinue {
public static void main (String args[]){
int MaxSeatCount = 5, TotalScreenCount = 2, seatCount = 0, screenCount = 0;
SkipScreen:
//System.out.println(screenCount);
while(screenCount < TotalScreenCount){
Branching - Unconditional
}
System.out.println("All Seats Filled in Screen "+(screenCount+1));
screenCount++;
}
}
}
Branching - Unconditional
Output:
Screen 1 Ticket Booking detail
Seats No Booked : 1
Seats No Booked : 2
Seats No Booked : 3
Seats No Booked : 4
Seats No Booked : 5
All Seats Filled in Screen 1
Screen 2 Ticket Booking detail
Seats No Booked : 1
Seat No 2 is Reserved
Seat No 3 is Reserved
Seats No Booked : 4
Seats No Booked : 5
All Seats Filled in Screen 2
Quiz
b) if else statement
Quiz
if (num>0)
System.out.println(“Positive Number\n”);
else
System.out.println(“Negative Number\n”);
System.out.println(“The number is %d”,num);
c) Positive Number
d) The number is 6
The number is 6
c) Positive Number
The number is 6
87 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Quiz
a) case b) break
c) default
Quiz
Quiz
a) while b) do…while
b) do…while
Quiz
a) 1 b) 9
c) 10 d) 11
b) 11
Quiz
7. Which of the following are true about the enhanced for loop?
A. It can iterate over an array or a Collection but not a Map.
B. Using an enhanced for loop prevents the code from going into
an infinite loop
C. Using an enhanced for loop on an array may cause infinite
loop.
D. An enhanced for loop can iterate over a Map.
E. You cannot find out the number of the current iteration while
iterating.
a) A,B,E b) A,B,C
c) B,C,E d) A,D,E
a) A,B,E
Quiz
8. What is printed as a result of the following code segment?
for (int k = 0; k < 20; k+=2)
{
if (k % 3 == 1)
System.out.print(k + " ");
}
a) 0 2 4 6 8 10 12 14 16 18 b) 4,6
c) 4,10,16 d) 0,6,12,18
c) 4,10,16
Quiz
9. What is the output after the following code has been executed?
class FlowControl1 {
System.out.println(“Hello Friend");
else
}
94 Control Flow Statements| © SmartCliff | Internal | Version 1.0
Control Flow Statements
Quiz
10. What is stored in the variable result after the following code has been
executed?
class FlowControl2{
public static void main(String args[]){
int index = 0;
int result = 1;
while ( true ){
++index;
if ( index % 2 == 0 )
continue;
else if ( index % 5 == 0 )
break;
result *= 3;
}
}
}
Quiz
11. What is the output after the following code has been executed?
class FlowControl3 {
boolean b = true;
if(!b) {
System.out.println("HELLO");
} else {
System.out.println("BYE");
Quiz
12. What is the output after the following code has been executed?
class FlowControl4 {
System.out.println("HIII");
System.out.println("BYE");
Quiz
13. What is stored in the result after the following code has been executed?
class Test {
do {
System.out.print(1);
do {
System.out.print(2);
} while (false);
} while (false);