SlideShare a Scribd company logo
1 of 70
Java
Programming
Dr. Meenu & Dr. Riman Mandal & Shamim
Ahmad
Faculty
School of Engineering & Technology (SOET)
K. R. Managalam University
Java Control Structure
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 1/67
Session Agenda
Session
1
Java Control Structure -
Decision Making
if, if-else,
if-else-ifladder
The switch-case
Statement
Practical
Scenarios Q&A
Session
2
Java Control Structure -
Looping
for, while,
do-while
Jump Statements -
break, continue
Practical
Scenarios Q&A
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 2/67
Key Learning Outcome
Gain a comprehensive understanding of
Java’s control flow statements.
Learn how to use conditional statements
for decision-making.
Discover the use cases for different
variations of loop structures.
Utilize jump statements to alter control flow
within loops.
Apply control structures in real-world
programming problem-solving.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 3/67
Session 1
Session 1 emphasizes on Decision Making in
Java
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 4/67
Importance of Control Structures
Control structures are the cornerstone of
programming logic.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 5/67
Importance of Control
Structures
They Provide the ability
to Make
Decisions
Repeat Tasks
Control Flow
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 6/67
Importance of Control Structures
They Provide the ability
to Make Decisions
Execute code blocks selectively based on
conditions.
Repeat
Tasks
Control Flow
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 7/67
Importance of Control Structures
They Provide the ability
to Make
Decisions
Repeat Tasks
Automate code execution to process data
efficiently.
Control Flow
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 8/67
Importance of Control Structures
They Provide the ability
to Make
Decisions
Repeat Tasks
Control Flow
Break out of loops, skip iterations, and create
complex logic paths.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 9/67
Decision Makings
Conditional Skip/Jump - if
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 10/67
Decision Makings
Conditional Skip/Jump - if
Two-way Branch - if-else
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 10/67
Decision Makings
Conditional Skip/Jump - if
Two-way Branch - if-else
Hirerchical Decision - nested
if
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 10/67
Decision Makings
Conditional Skip/Jump - if
Two-way Branch - if-else
Hirerchical Decision - nested
if
Multiway Branch - if-else-ifladder,
switch-case
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 10/67
Conditional Skip/Jump
Use of ifStatement
You need to execute a code block only if a
single condition is true.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 11/67
Conditional Skip/Jump
Use of ifStatement
Synta
x
if (<binary_condition>){
//Statement 1
//Statement 2
.
.
.
//Statements if condition is true.
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 12/67
Conditional Skip/Jump
Use of ifStatement
Exampl
e
Excercis
e
int age = 25;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} [Complete]
WAP that inputs a number (N) and adds 5 to N if
N is odd then print it.
[Solution
]
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 13/67
Two-way Branch
Use of if-elseStatement
You have two distinct code blocks – one to execute if
a condition is true, and another to execute if the
condition is false.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 14/67
Two-way Branch
Use of if-elseStatement
Synta
x
if (<binary_condition>){
.
.
.
//Statements if condition is true.
} else{
.
.
.
//Statements if condition is false.
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 15/67
Two-way Branch
Use of if-elseStatement
Exampl
e
int number = 25;
if (number % 2 == 0){ System.out.println(number + "
is even.");
} else{
System.out.println(number + " is even.");
} [Complete
]
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 16/67
Two-way Branch: Excercise
Use of if-elseStatement
WAP to find the maximum among two numbers.
[Solution
]
WAP that inputs a number (N) and adds 7 to N if N is odd,
else add 4.
[Solution
]
WAP to create a simple number gussing game. First set a
secrect number and ask user to provide a input. If the
input matches to secrect number user wins, for mismatch
user loses. [Solution]
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 17/67
Nesting
Use of Nested if-elseStatements
You need to check multiple conditions in a
dependent manner. The inner ’if’ statements are
only evaluated if the outer ’if’ conditions are true.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 18/67
Nesting
Use of Nested if-elseStatements
Synta
x
if (<binary_condition1>){
//Statements if condition1 is true. [if
(<binary_condition2>){
//Statements if condition1 and condition2 is true.
} else{
//Statements if condition1 is true and condition2 is false.
}]
} else{
//Statements if condition1 is false. [if
(<binary_condition3>){
//Statements if condition1 is false and condition3 is true.
} else{
//Statements if condition1 and condition3 is false.
}]
}
Anything enclosed in […] means optional
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 19/67
Nesting
Use of Nested if-elseStatements
Example
1
int age = 23;
boolean hasLicense = true; if
(age >= 18) {
if (hasLicense) {
System.out.println("You are eligible to vote and drive.");
} else {
System.out.println("You are eligible to vote but cannot drive.");
}
} else {
System.out.println("You are not eligible to vote or drive.");
} [Complete]
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 20/67
Nesting
Use of Nested if-elseStatements
Example 2: Find maximum amoung three
numbers
if(a>b)
if (a>c)
printf(“A is max.”); else
printf(“C is max.”);
else
if (b>c)
printf(“B is max.”); else
printf(“C is max.”);
[Complete]
Use your creativity and desing alternative
solutions to solve the same problem.
For single statment within a block {…} is not mandatory
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 21/67
Nesting: Excercise
Use of Nested if-elseStatements
WAP that determines whether a given year is a leap year or not. A
year is a leap year if it is divisible by 4 but not divisible by 100, or if it
is divisible by 400.
WAP that calculates the discount percentage for a customer’s
purchase based on the purchase amount and customer loyalty. If the
purchase amount is greater than 100 and the customer has been loyal
(member for more than a year), they get a 10% discount; otherwise,
they get a 5
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 22/67
Multi-way Branching
Use of if-else-iflader Statements
You need to check a sequence of multiple conditions
and execute the first block whose condition is
true.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 23/67
Multi-way Branching
Use of if-else-iflader Statements
Synta
x if (condition1) {
// Code block 1
} else if (condition2) {
// Code block 2
} else if (condition3) {
// Code block 3
}
...
else {
// Default code block
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 24/67
Multi-way Branching
Use of if-else-iflader Statements
Example 1: Grade
Claculation
int marks = 67;
if(marks >= 90)
printf(“Grade = A+”); else
if (marks >= 80)
printf(“Grade = A”);
else if (marks >= 70)
printf(“Grade = B”);
else if (marks >= 60)
printf(“Grade = C”); else
if (marks >= 40)
printf(“Grade = D”);
else
printf(“Grade = Fail”);
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 25/67
Multi-way Branching
Use of if-else-iflader Statements
Example 2: Categorizing
Temperatures
double temperature = 12;
if (temperature < 0) {
System.out.println("Freezing");
} else if (temperature >= 0 && temperature < 15) {
System.out.println("Cold");
} else if (temperature >= 15 && temperature < 25) {
System.out.println("Mild");
} else if (temperature >= 25 && temperature < 35) {
System.out.println("Warm");
} else {
System.out.println("Hot");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 26/67
Multi-way Branching
Use of if-else-iflader Statements
Example 3: Day of the
Week int dayNumber = 3;
if (dayNumber == 1) {
System.out.println("Monday");
} else if (dayNumber == 2) {
System.out.println("Tuesday");
} else if (dayNumber == 3) {
System.out.println("Wednesday");
} else if (dayNumber == 4) {
System.out.println("Thursday");
}
...
else {
System.out.println("Invalid day number");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 27/67
Multi-way Branching: Code It
Yourself
Solution to Quadratic equation: Ax2 + Bx+ C = 0
1. Start
2. Input A, B, C.
3. If A=0 then print “This is not a quadratic equation” and stop.
4. D = B^2 - 4AC
5. L = -B / 2A
6. If D<0 then print “No real root found.” and stop.
7. Else If D=0 then print Only one root: L and stop.
8. Else
9. X1 = L + (√D/2A)
10. X2 = L - (√D/2A)
11. Print Root1 = X1 and Root2 = X2
12. stop
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 28/67
Brainstorming Session: Fill in the
Blanks
if, if-else, if-else-ifladder, nested if
1 The statement is used to execute a code block ifa condition is
true.
2 The statement is used to execute a different code block ifthe
original condition is false.
3 To test multiple conditions sequentially, you would use the
construct.
4 The elsestatement associated with a nested if statement is
executed only when of the preceding ifconditions are true.
5 In an if-else ladder, if the condition specified in the if statement
evaluates to true, the corresponding block of code is executed, and
the control then exits to the of the ladder.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 29/67
Brainstorming Session: Fill in the
Blanks
if, if-else, if-else-ifladder, nested if
1 The if statement is used to execute a code block ifa condition is
true.
2 The else statement is used to execute a different code block if
the original condition is false.
3 To test multiple conditions sequentially, you would use the
if-else-if ladder construct.
4 The elsestatement associated with a nested if statement is
executed only when none of the preceding ifconditions are true.
5 In an if-else ladder, if the condition specified in the if statement
evaluates to true, the corresponding block of code is executed, and
the control then exits to the end of the ladder.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 30/67
Multi-way Branching: Excercise I
Use of if-else-iflader Statements
WAP that calculates a person’s Body Mass Index (BMI) based on
their height (in meters) and weight (in kilograms) inputs. Then,
classify the BMI into categories according to the following criteria:
Underweight: BMI less than
18.5 Normal weight: BMI 18.5
to 24.9
Overweight: BMI 25 to 29.9
Obesity: BMI 30 or greater
Hint : BMI = weight(kg)/height(m)2
WAP that converts temperature from Celsius to Fahrenheit and
vice versa. The program should prompt the user to choose the
conversion direction and input the temperature accordingly.
Nested if statements can be used to handle the conversion logic.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 31/67
Multi-way Branching: Excercise II
Use of if-else-iflader Statements
Create a program that takes three sides of a triangle as input and
determines whether the triangle is equilateral, isosceles, or scalene.
Here are the definitions:
Equilateral triangle: All three sides are equal in
length. Isosceles triangle: Two sides are equal in
length.
Scalene triangle: All three sides have different lengths.
WAP that calculates the price of a movie ticket based on the age of
the customer and the time of the show. The ticket prices are as
follows: Children (age <= 12): Rs. 5 before 6 PM, Rs. 8 after 6 PM
Adults (age > 12 and age <= 65): Rs. 10 before 6 PM, Rs. 12 after 6
PM
Seniors (age > 65): Rs. 8 for all show times.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 32/67
Multi-way Branching: Excercise III
Use of if-else-iflader Statements
WAP that calculates the total price for items in an online shopping
cart. Apply discounts based on the total purchase amount as follows:
10% discount for purchases above Rs. 100 but less than Rs.
200. 15% discount for purchases above Rs. 200 but less than
Rs. 500. 20% discount for purchases of Rs. 500 or more.
WAP to compute the electric bill based on the specifications provided
in your household electricity bill. The bill includes both fixed charges
and variable charges, with the variable charges dependent on the
number of units consumed.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 33/67
Multi-way Branching: Excercise I
Use of if-else-iflader Statements
WAP that calculates a person’s Body Mass Index (BMI) based on
their height (in meters) and weight (in kilograms) inputs. Then,
classify the BMI into categories according to the following criteria:
Underweight: BMI less than
18.5 Normal weight: BMI 18.5
to 24.9
Overweight: BMI 25 to 29.9
Obesity: BMI 30 or greater
Hint : BMI = weight(kg)/height(m)2
WAP that converts temperature from Celsius to Fahrenheit and
vice versa. The program should prompt the user to choose the
conversion direction and input the temperature accordingly.
Nested if statements can be used to handle the conversion logic.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 34/67
Multi-way Branching: Excercise II
Use of if-else-iflader Statements
Create a program that takes three sides of a triangle as input and
determines whether the triangle is equilateral, isosceles, or scalene.
Here are the definitions:
Equilateral triangle: All three sides are equal in
length. Isosceles triangle: Two sides are equal in
length.
Scalene triangle: All three sides have different lengths.
WAP that calculates the price of a movie ticket based on the age of
the customer and the time of the show. The ticket prices are as
follows: Children (age <= 12): Rs. 5 before 6 PM, Rs. 8 after 6 PM
Adults (age > 12 and age <= 65): Rs. 10 before 6 PM, Rs. 12 after 6
PM
Seniors (age > 65): Rs. 8 for all show times.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 35/67
Multi-way Branching: Excercise III
Use of if-else-iflader Statements
WAP that calculates the total price for items in an online shopping
cart. Apply discounts based on the total purchase amount as follows:
10% discount for purchases above Rs. 100 but less than Rs.
200. 15% discount for purchases above Rs. 200 but less than
Rs. 500. 20% discount for purchases of Rs. 500 or more.
WAP to compute the electric bill based on the specifications provided
in your household electricity bill. The bill includes both fixed charges
and variable charges, with the variable charges dependent on the
number of units consumed.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 36/67
Predict the output (if-else) I
Brainstorming Session Continues . . .
Snipet
1
int x = 10; if (x
> 5) {
if (x < 15) {
System.out.println("x is between 5 and 15");
} else {
System.out.println("x is greater than or equal to 15");
}
} else {
System.out.println("x is less than or equal to 5");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 37/67
Predict the output (if-else) II
Brainstorming Session Continues . . .
Snipet
2
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
} else if (age >= 13) { System.out.println("You are a
teenager.");
} else {
System.out.println("You are a child.");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 38/67
Predict the output (if-else) III
Brainstorming Session Continues . . .
Snipet
3
int num = 7;
if (num % 2 == 0) {
System.out.println("Even");
} else if (num % 3 == 0) {
System.out.println("Divisible by 3 but not even");
} else {
System.out.println("Not even or divisible by 3");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 39/67
Predict the output (if-else) IV
Brainstorming Session Continues . . .
Snipet
4
int a = 10, b = 20, c = 30; if (a >
b && a > c) {
System.out.println("a is the largest number.");
} else if (b > a && b > c) {
System.out.println("b is the largest number.");
} else {
System.out.println("c is the largest number.");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 40/67
Predict the output (if-else) V
Brainstorming Session Continues . . .
Snipet
5
int num = 10; if
(num > 0) {
if (num % 2 == 0) {
System.out.println("Positive even number.");
} else {
System.out.println("Positive odd number.");
}
} else {
System.out.println("Not a positive number.");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 41/67
Predict the output (if-else) VI
Brainstorming Session Continues . . .
Snipet
6
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 80) {
System.out.println("Grade B");
} else if (marks >= 70) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 42/67
Predict the output (if-else) VII
Brainstorming Session Continues . . .
Snipet
7
int num = 10; if
(num > 0) {
if (num % 2 == 0) {
System.out.println("Positive even number.");
} else {
System.out.println("Positive odd number.");
}
} else if (num < 0) { System.out.println("Negative
number.");
} else {
System.out.println("Zero.");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 43/67
Predict the output (if-else) VIII
Brainstorming Session Continues . . .
Snipet
8
int num = 5; if
(num > 0) {
if (num < 10) {
System.out.println("Single digit positive number.");
} else {
System.out.println("Positive number, but not single digit."
}
} else {
System.out.println("Non-positive number.");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 44/67
Predict the output (if-else) IX
Brainstorming Session Continues . . .
Snipet
9
int x = 5, y = 10; if (x
> 0) {
if (y > 0) {
System.out.println("Both x and y are positive.");
} else {
System.out.println("x is positive but y is not.");
}
} else {
System.out.println("x is not positive.");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 45/67
Predict the output (if-else) X
Brainstorming Session Continues . . .
Snipet
10
int a = 10, b = 20, c = 30; if (a >
b) {
if (a > c) {
System.out.println("a is the largest number.");
} else {
System.out.println("c is the largest number.");
}
} else {
if (b > c) {
System.out.println("b is the largest number.");
} else {
System.out.println("c is the largest number.");
}
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 46/67
Multi-way Branching: switch-case
The switch-casestatement is used to perform
different actions based on the value of a variable
or expression.
It provides a cleaner and more efficient
alternative to long if-else-ifchains when dealing
with multiple options.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 47/67
switch-caseStatement
Syntax
Synta
x
switch (<control-var>) {
case <value1>:
// code block 1
case <value2>:
// code block 2
case <value3>:
// code block 3
// more cases...
[default:
// default code block]
}
Only supports int,
char, string, enum
data types for control
variable
Does not support
double
data type
Checks only for
equality (==)
execute code block if
control variable
equals(==) case
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 48/67
switch-caseFall Through
is switch-caseincompleted Without breakstatement?
Senari
o
int x = 3;
switch (x) {
case 1:
System.out.print("1"); case
3:
System.out.print("3");
case 5: System.out.print("5");
case 7:
System.out.print("7");
default:
System.out.print("No Match");
}
Outpu
t
The output will be: 357No Match
When control variable
matches with a case value
rest of the cases are ignored
and all the statements are
executed
breakis used to resolve
the problem
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 49/67
switch-casewith breakStatement
Syntax
Synta
x
switch (<control-var>) { case
<value1>:
// code block 1
break;
case <value2>:
// code block 2
break;
case <value3>:
// code block 3
break;
// more cases with break...
[default:
// default code block]
}
When control variable
matches
with a case value only the
statements associated with
the case block is executed.
breakstatement is used to
exit
the switch statement to end
of switch statement.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 50/67
switch-casewith breakStatement
Example 1
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Great job!");
break;
case 'C':
System.out.println("Well done.");
break;
case 'D':
System.out.println("Youpassed.");
break;
case 'F':
System.out.println("Better try again.");
break;
default:
System.out.println("Invalid grade.");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 51/67
switch-casewith breakStatement
Example 2
int choice = 2;
switch (choice) {
case 1:
System.out.println("You ordered a Cappuccino."); break;
case 2:
System.out.println("You ordered an Espresso."); break;
case 3:
System.out.println("You ordered a Latte."); break;
default:
System.out.println("Invalid menu selection.");
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 52/67
Menu Driven Programming I
switch-casewith breakStatement: Example 3
using java.util.Scanner;
class TempConversion{
public static void main(String args[]){ Scanner input =
new Scanner (System.in);
System.out.println("Enter 1 for Celsius to Fahrenheit");
System.out.println("Enter 2 for Fahrenheit to Celsius");
System.out.println("Enter your choice: ");
int choice = input.nextInt();
double tempInput, tempOutput;
switch (choice) {
case 1:
System.out.print("Enter Temperature in Celsius: "); tempInput
= input.nextDouble();
tempOutput = (tempInput * 9 / 5) + 32;
System.out.println(tempInput + " oC is equal to "
+ tempOutput + " oF.");
break;
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 53/67
Menu Driven Programming II
switch-casewith breakStatement: Example 3
case 2:
System.out.print("Enter Temperature in Fahrenheit: "); tempInput
= input.nextDouble();
tempOutput = (tempInput - 32) * 5 / 9;
System.out.println(tempInput + " oC is equal to "
+ tempOutput + " oF.");
break;
default:
System.out.println("Invalid menu selection.");
}
}
}
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 54/67
Brainstorming Session: Fill in the
Blanks
switch-case
1 In Java, the switch statement is used to perform different actions
based on the value of a .
2 The default case in a switch statement is executed if none of the
other
match the value of the expression.
3 The break statement in a switch statement is used to exit the
switch block and prevents .
4 If a break statement is omitted in a case block, control will fall
through to the next block.
5 The switch statement is considered an alternative to long
chain
s when dealing with multiple options.
6 The default case in a switch statement is .
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 55/67
Brainstorming Session: Fill in the
Blanks
switch-case
1 In Java, the switch statement is used to perform different actions
based on the value of a control variable .
2 The default case in a switch statement is executed if none of the
other
cases match the value of the expression.
3 The break statement in a switch statement is used to exit the
switch block and prevents fall-through .
4 If a break statement is omitted in a case block, control will fall
through to the next case block.
5 The switch statement is considered an alternative to long if-
else chains when dealing with multiple options.
6 The default case in a switch statement is optional
.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 56/67
switch-case: Excercise I
Calculator Program: Write a Java program to implement a
simple calculator that performs addition, subtraction,
multiplication, and division based on the user’s choice using a
switch-case statement.
Grade Calculator: Develop a Java program that takes a student’s
score as input and prints out their corresponding grade (A, B, C, D,
F) based on the score using a switch-case statement.
Month Name: Create a Java program that takes an integer
representing a month (1 for January, 2 for February, etc.) as input
and prints out the name of the month using a switch-case statement.
Day of the Week: Write a Java program that takes an integer
representing a day of the week (1 for Monday, 2 for Tuesday, etc.)
as
input and prints out the name of the day using a switch-case
statement.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 57/67
switch-case: Excercise II
Simple ATM Machine: Develop a Java program to simulate a
simple ATM machine. The program should allow users to perform
operations such as checking balance, withdrawing money, and
depositing money using switch-case statements for menu options.
Traffic Light Simulator: Write a Java program to simulate a traffic light.
The program should take an integer representing the current state of
the traffic light (1 for red, 2 for yellow, 3 for green) as input and print
out the corresponding action (stop, slow down, go) using a switch-
case statement.
Simple Menu Driven System: Create a Java program that
implements a simple menu-driven system. The program should
display a menu with options such as add, delete, update, and exit.
Implement each option
using switch-case
statements.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 58/67
switch-case: Excercise III
Language Selector: Develop a Java program that takes an integer
representing a language (1 for English, 2 for Spanish, 3 for French,
etc.) as input and prints out a greeting message in the selected
language using switch-case statements.
Season Identifier: Write a Java program that takes an integer
representing a month (1 for January, 2 for February, etc.) as input and
prints out the corresponding season (spring, summer, fall, winter)
using a switch-case statement.
Simple Game: Develop a Java program for a simple game where the
user guesses a number between 1 and 10. The program should
generate a random number and compare it with the user’s guess.
Provide feedback using switch-case statements to indicate if the
guess was too high, too low, or correct.
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 59/67
Predict the output (switch-case) I
Brainstorming Session Continues . . .
Snipet 1
int x = 3; String
result; switch (x)
{
case 1:
case 2:
result = "One or Two";
break;
case 3:
case 4:
result = "Three or Four";
break;
default:
result = "Other";
}
System.out.println(result);
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 60/67
Predict the output (switch-case) II
Brainstorming Session Continues . . .
Snipet 2
int day = 7; String
dayOfWeek; switch
(day) {
case 1:
dayOfWeek = "Monday";
break;
case 2:
dayOfWeek = "Tuesday";
break;
case 3:
dayOfWeek = "Wednesday";
break;
case 4:
dayOfWeek = "Thursday";
break;
case 5:
dayOfWeek = "Friday";
break;
default:
dayOfWeek = "Weekend";
}
System.out.println(dayOfWeek);
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 61/67
Predict the output (switch-case) III
Brainstorming Session Continues . . .
Snipet 3
char grade = 'B';
String message;
switch (grade) {
case 'A':
message = "Excellent!";
break;
case 'B':
message = "Good!";
break;
case 'C':
message = "Average";
break;
default:
message = "Need Improvement";
}
System.out.println(message);
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 62/67
Predict the output (switch-case) IV
Brainstorming Session Continues . . .
Snipet 4
int month = 9;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Invalid month";
}
System.out.println(season);
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 63/67
Predict the output (switch-case) V
Brainstorming Session Continues . . .
Snipet 5
int num = 10; String
result; switch (num %
2) {
case 0:
result = "Even";
break;
case 1:
result = "Odd";
break;
default:
result = "Not an integer";
}
System.out.println(result);
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 64/67
Predict the output (switch-case) VI
Brainstorming Session Continues . . .
Snipet 6
int marks = 75;
String grade;
switch (marks / 10) {
case 10:
case 9:
grade = "A";
break;
case 8:
grade = "B";
break;
case 7:
grade = "C";
break;
case 6:
grade = "D";
break;
default:
grade = "F";
}
System.out.println(grade);
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 65/67
Predict the output (switch-case) VII
Brainstorming Session Continues . . .
Snipet 7
int month = 2;
int year = 2024;
int days;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if ((year % 4 == 0 && year % 100 != 0)
|| (year % 400 == 0))
days = 29;
else
days = 28;
break;
default:
days = -1;
}
System.out.println("Number of days: " + days);
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 66/67
Session 2
Session 2 will be continued with loop structures in
java
Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 67/67

More Related Content

Similar to Java Control Structure Session 1 Complete (1).pptx

control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)Prashant Sharma
 
Informatica data warehousing_job_interview_preparation_guide
Informatica data warehousing_job_interview_preparation_guideInformatica data warehousing_job_interview_preparation_guide
Informatica data warehousing_job_interview_preparation_guideDhanasekar T
 
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...Juan Cruz Nores
 
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...WebStackAcademy
 
13 javascript techniques to improve your code
13 javascript techniques to improve your code13 javascript techniques to improve your code
13 javascript techniques to improve your codeSurendra kumar
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorialSrinath Perera
 
Unit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleUnit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleumaghosal12101974
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner Huda Alameen
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsWebStackAcademy
 
Design Summit - Advanced policy state management - John Hardy
Design Summit - Advanced policy state management - John HardyDesign Summit - Advanced policy state management - John Hardy
Design Summit - Advanced policy state management - John HardyManageIQ
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...Mario Fusco
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Kernel Training
 

Similar to Java Control Structure Session 1 Complete (1).pptx (20)

Week 4
Week 4Week 4
Week 4
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
Informatica data warehousing_job_interview_preparation_guide
Informatica data warehousing_job_interview_preparation_guideInformatica data warehousing_job_interview_preparation_guide
Informatica data warehousing_job_interview_preparation_guide
 
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
 
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
 
13 javascript techniques to improve your code
13 javascript techniques to improve your code13 javascript techniques to improve your code
13 javascript techniques to improve your code
 
Ch 6 randomization
Ch 6 randomizationCh 6 randomization
Ch 6 randomization
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Rules Programming tutorial
Rules Programming tutorialRules Programming tutorial
Rules Programming tutorial
 
Unit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleUnit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment example
 
Sql optimize
Sql optimizeSql optimize
Sql optimize
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
 
Design Summit - Advanced policy state management - John Hardy
Design Summit - Advanced policy state management - John HardyDesign Summit - Advanced policy state management - John Hardy
Design Summit - Advanced policy state management - John Hardy
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
Qm sampling scheme
Qm sampling schemeQm sampling scheme
Qm sampling scheme
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 

More from RahulSingh190790

ETCS262A-Analysis of design Algorithm.pptx
ETCS262A-Analysis of design Algorithm.pptxETCS262A-Analysis of design Algorithm.pptx
ETCS262A-Analysis of design Algorithm.pptxRahulSingh190790
 
Fundamntl of computer programing in python.pptx
Fundamntl of computer programing in python.pptxFundamntl of computer programing in python.pptx
Fundamntl of computer programing in python.pptxRahulSingh190790
 
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdfDr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdfRahulSingh190790
 
Seminar or Progress Viva PPT format 2022.pptx
Seminar or Progress Viva PPT format 2022.pptxSeminar or Progress Viva PPT format 2022.pptx
Seminar or Progress Viva PPT format 2022.pptxRahulSingh190790
 
Synopsis Lokesh Pawar.pptx
Synopsis Lokesh Pawar.pptxSynopsis Lokesh Pawar.pptx
Synopsis Lokesh Pawar.pptxRahulSingh190790
 

More from RahulSingh190790 (6)

ETCS262A-Analysis of design Algorithm.pptx
ETCS262A-Analysis of design Algorithm.pptxETCS262A-Analysis of design Algorithm.pptx
ETCS262A-Analysis of design Algorithm.pptx
 
Fundamntl of computer programing in python.pptx
Fundamntl of computer programing in python.pptxFundamntl of computer programing in python.pptx
Fundamntl of computer programing in python.pptx
 
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdfDr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
 
Seminar or Progress Viva PPT format 2022.pptx
Seminar or Progress Viva PPT format 2022.pptxSeminar or Progress Viva PPT format 2022.pptx
Seminar or Progress Viva PPT format 2022.pptx
 
Synopsis Lokesh Pawar.pptx
Synopsis Lokesh Pawar.pptxSynopsis Lokesh Pawar.pptx
Synopsis Lokesh Pawar.pptx
 
showprojfile.asp.pdf
showprojfile.asp.pdfshowprojfile.asp.pdf
showprojfile.asp.pdf
 

Recently uploaded

NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024EMMANUELLEFRANCEHELI
 
Geometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdfGeometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdfJNTUA
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxMustafa Ahmed
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfEr.Sonali Nasikkar
 
21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological university21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological universityMohd Saifudeen
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxMANASINANDKISHORDEOR
 
Dynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxDynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxMustafa Ahmed
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisDr.Costas Sachpazis
 
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...Amil baba
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxKarpagam Institute of Teechnology
 
Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2T.D. Shashikala
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalSwarnaSLcse
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxkalpana413121
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashidFaiyazSheikh
 
Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)NareenAsad
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.benjamincojr
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxMustafa Ahmed
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...IJECEIAES
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...josephjonse
 
Seizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networksSeizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networksIJECEIAES
 

Recently uploaded (20)

NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
Geometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdfGeometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdf
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptx
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
 
21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological university21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological university
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
Dynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxDynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptx
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 
Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference Modal
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptx
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
 
Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Seizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networksSeizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networks
 

Java Control Structure Session 1 Complete (1).pptx

  • 1. Java Programming Dr. Meenu & Dr. Riman Mandal & Shamim Ahmad Faculty School of Engineering & Technology (SOET) K. R. Managalam University Java Control Structure Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 1/67
  • 2. Session Agenda Session 1 Java Control Structure - Decision Making if, if-else, if-else-ifladder The switch-case Statement Practical Scenarios Q&A Session 2 Java Control Structure - Looping for, while, do-while Jump Statements - break, continue Practical Scenarios Q&A Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 2/67
  • 3. Key Learning Outcome Gain a comprehensive understanding of Java’s control flow statements. Learn how to use conditional statements for decision-making. Discover the use cases for different variations of loop structures. Utilize jump statements to alter control flow within loops. Apply control structures in real-world programming problem-solving. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 3/67
  • 4. Session 1 Session 1 emphasizes on Decision Making in Java Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 4/67
  • 5. Importance of Control Structures Control structures are the cornerstone of programming logic. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 5/67
  • 6. Importance of Control Structures They Provide the ability to Make Decisions Repeat Tasks Control Flow Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 6/67
  • 7. Importance of Control Structures They Provide the ability to Make Decisions Execute code blocks selectively based on conditions. Repeat Tasks Control Flow Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 7/67
  • 8. Importance of Control Structures They Provide the ability to Make Decisions Repeat Tasks Automate code execution to process data efficiently. Control Flow Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 8/67
  • 9. Importance of Control Structures They Provide the ability to Make Decisions Repeat Tasks Control Flow Break out of loops, skip iterations, and create complex logic paths. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 9/67
  • 10. Decision Makings Conditional Skip/Jump - if Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 10/67
  • 11. Decision Makings Conditional Skip/Jump - if Two-way Branch - if-else Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 10/67
  • 12. Decision Makings Conditional Skip/Jump - if Two-way Branch - if-else Hirerchical Decision - nested if Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 10/67
  • 13. Decision Makings Conditional Skip/Jump - if Two-way Branch - if-else Hirerchical Decision - nested if Multiway Branch - if-else-ifladder, switch-case Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 10/67
  • 14. Conditional Skip/Jump Use of ifStatement You need to execute a code block only if a single condition is true. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 11/67
  • 15. Conditional Skip/Jump Use of ifStatement Synta x if (<binary_condition>){ //Statement 1 //Statement 2 . . . //Statements if condition is true. } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 12/67
  • 16. Conditional Skip/Jump Use of ifStatement Exampl e Excercis e int age = 25; if (age >= 18) { System.out.println("You are eligible to vote."); } [Complete] WAP that inputs a number (N) and adds 5 to N if N is odd then print it. [Solution ] Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 13/67
  • 17. Two-way Branch Use of if-elseStatement You have two distinct code blocks – one to execute if a condition is true, and another to execute if the condition is false. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 14/67
  • 18. Two-way Branch Use of if-elseStatement Synta x if (<binary_condition>){ . . . //Statements if condition is true. } else{ . . . //Statements if condition is false. } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 15/67
  • 19. Two-way Branch Use of if-elseStatement Exampl e int number = 25; if (number % 2 == 0){ System.out.println(number + " is even."); } else{ System.out.println(number + " is even."); } [Complete ] Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 16/67
  • 20. Two-way Branch: Excercise Use of if-elseStatement WAP to find the maximum among two numbers. [Solution ] WAP that inputs a number (N) and adds 7 to N if N is odd, else add 4. [Solution ] WAP to create a simple number gussing game. First set a secrect number and ask user to provide a input. If the input matches to secrect number user wins, for mismatch user loses. [Solution] Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 17/67
  • 21. Nesting Use of Nested if-elseStatements You need to check multiple conditions in a dependent manner. The inner ’if’ statements are only evaluated if the outer ’if’ conditions are true. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 18/67
  • 22. Nesting Use of Nested if-elseStatements Synta x if (<binary_condition1>){ //Statements if condition1 is true. [if (<binary_condition2>){ //Statements if condition1 and condition2 is true. } else{ //Statements if condition1 is true and condition2 is false. }] } else{ //Statements if condition1 is false. [if (<binary_condition3>){ //Statements if condition1 is false and condition3 is true. } else{ //Statements if condition1 and condition3 is false. }] } Anything enclosed in […] means optional Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 19/67
  • 23. Nesting Use of Nested if-elseStatements Example 1 int age = 23; boolean hasLicense = true; if (age >= 18) { if (hasLicense) { System.out.println("You are eligible to vote and drive."); } else { System.out.println("You are eligible to vote but cannot drive."); } } else { System.out.println("You are not eligible to vote or drive."); } [Complete] Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 20/67
  • 24. Nesting Use of Nested if-elseStatements Example 2: Find maximum amoung three numbers if(a>b) if (a>c) printf(“A is max.”); else printf(“C is max.”); else if (b>c) printf(“B is max.”); else printf(“C is max.”); [Complete] Use your creativity and desing alternative solutions to solve the same problem. For single statment within a block {…} is not mandatory Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 21/67
  • 25. Nesting: Excercise Use of Nested if-elseStatements WAP that determines whether a given year is a leap year or not. A year is a leap year if it is divisible by 4 but not divisible by 100, or if it is divisible by 400. WAP that calculates the discount percentage for a customer’s purchase based on the purchase amount and customer loyalty. If the purchase amount is greater than 100 and the customer has been loyal (member for more than a year), they get a 10% discount; otherwise, they get a 5 Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 22/67
  • 26. Multi-way Branching Use of if-else-iflader Statements You need to check a sequence of multiple conditions and execute the first block whose condition is true. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 23/67
  • 27. Multi-way Branching Use of if-else-iflader Statements Synta x if (condition1) { // Code block 1 } else if (condition2) { // Code block 2 } else if (condition3) { // Code block 3 } ... else { // Default code block } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 24/67
  • 28. Multi-way Branching Use of if-else-iflader Statements Example 1: Grade Claculation int marks = 67; if(marks >= 90) printf(“Grade = A+”); else if (marks >= 80) printf(“Grade = A”); else if (marks >= 70) printf(“Grade = B”); else if (marks >= 60) printf(“Grade = C”); else if (marks >= 40) printf(“Grade = D”); else printf(“Grade = Fail”); Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 25/67
  • 29. Multi-way Branching Use of if-else-iflader Statements Example 2: Categorizing Temperatures double temperature = 12; if (temperature < 0) { System.out.println("Freezing"); } else if (temperature >= 0 && temperature < 15) { System.out.println("Cold"); } else if (temperature >= 15 && temperature < 25) { System.out.println("Mild"); } else if (temperature >= 25 && temperature < 35) { System.out.println("Warm"); } else { System.out.println("Hot"); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 26/67
  • 30. Multi-way Branching Use of if-else-iflader Statements Example 3: Day of the Week int dayNumber = 3; if (dayNumber == 1) { System.out.println("Monday"); } else if (dayNumber == 2) { System.out.println("Tuesday"); } else if (dayNumber == 3) { System.out.println("Wednesday"); } else if (dayNumber == 4) { System.out.println("Thursday"); } ... else { System.out.println("Invalid day number"); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 27/67
  • 31. Multi-way Branching: Code It Yourself Solution to Quadratic equation: Ax2 + Bx+ C = 0 1. Start 2. Input A, B, C. 3. If A=0 then print “This is not a quadratic equation” and stop. 4. D = B^2 - 4AC 5. L = -B / 2A 6. If D<0 then print “No real root found.” and stop. 7. Else If D=0 then print Only one root: L and stop. 8. Else 9. X1 = L + (√D/2A) 10. X2 = L - (√D/2A) 11. Print Root1 = X1 and Root2 = X2 12. stop Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 28/67
  • 32. Brainstorming Session: Fill in the Blanks if, if-else, if-else-ifladder, nested if 1 The statement is used to execute a code block ifa condition is true. 2 The statement is used to execute a different code block ifthe original condition is false. 3 To test multiple conditions sequentially, you would use the construct. 4 The elsestatement associated with a nested if statement is executed only when of the preceding ifconditions are true. 5 In an if-else ladder, if the condition specified in the if statement evaluates to true, the corresponding block of code is executed, and the control then exits to the of the ladder. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 29/67
  • 33. Brainstorming Session: Fill in the Blanks if, if-else, if-else-ifladder, nested if 1 The if statement is used to execute a code block ifa condition is true. 2 The else statement is used to execute a different code block if the original condition is false. 3 To test multiple conditions sequentially, you would use the if-else-if ladder construct. 4 The elsestatement associated with a nested if statement is executed only when none of the preceding ifconditions are true. 5 In an if-else ladder, if the condition specified in the if statement evaluates to true, the corresponding block of code is executed, and the control then exits to the end of the ladder. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 30/67
  • 34. Multi-way Branching: Excercise I Use of if-else-iflader Statements WAP that calculates a person’s Body Mass Index (BMI) based on their height (in meters) and weight (in kilograms) inputs. Then, classify the BMI into categories according to the following criteria: Underweight: BMI less than 18.5 Normal weight: BMI 18.5 to 24.9 Overweight: BMI 25 to 29.9 Obesity: BMI 30 or greater Hint : BMI = weight(kg)/height(m)2 WAP that converts temperature from Celsius to Fahrenheit and vice versa. The program should prompt the user to choose the conversion direction and input the temperature accordingly. Nested if statements can be used to handle the conversion logic. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 31/67
  • 35. Multi-way Branching: Excercise II Use of if-else-iflader Statements Create a program that takes three sides of a triangle as input and determines whether the triangle is equilateral, isosceles, or scalene. Here are the definitions: Equilateral triangle: All three sides are equal in length. Isosceles triangle: Two sides are equal in length. Scalene triangle: All three sides have different lengths. WAP that calculates the price of a movie ticket based on the age of the customer and the time of the show. The ticket prices are as follows: Children (age <= 12): Rs. 5 before 6 PM, Rs. 8 after 6 PM Adults (age > 12 and age <= 65): Rs. 10 before 6 PM, Rs. 12 after 6 PM Seniors (age > 65): Rs. 8 for all show times. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 32/67
  • 36. Multi-way Branching: Excercise III Use of if-else-iflader Statements WAP that calculates the total price for items in an online shopping cart. Apply discounts based on the total purchase amount as follows: 10% discount for purchases above Rs. 100 but less than Rs. 200. 15% discount for purchases above Rs. 200 but less than Rs. 500. 20% discount for purchases of Rs. 500 or more. WAP to compute the electric bill based on the specifications provided in your household electricity bill. The bill includes both fixed charges and variable charges, with the variable charges dependent on the number of units consumed. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 33/67
  • 37. Multi-way Branching: Excercise I Use of if-else-iflader Statements WAP that calculates a person’s Body Mass Index (BMI) based on their height (in meters) and weight (in kilograms) inputs. Then, classify the BMI into categories according to the following criteria: Underweight: BMI less than 18.5 Normal weight: BMI 18.5 to 24.9 Overweight: BMI 25 to 29.9 Obesity: BMI 30 or greater Hint : BMI = weight(kg)/height(m)2 WAP that converts temperature from Celsius to Fahrenheit and vice versa. The program should prompt the user to choose the conversion direction and input the temperature accordingly. Nested if statements can be used to handle the conversion logic. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 34/67
  • 38. Multi-way Branching: Excercise II Use of if-else-iflader Statements Create a program that takes three sides of a triangle as input and determines whether the triangle is equilateral, isosceles, or scalene. Here are the definitions: Equilateral triangle: All three sides are equal in length. Isosceles triangle: Two sides are equal in length. Scalene triangle: All three sides have different lengths. WAP that calculates the price of a movie ticket based on the age of the customer and the time of the show. The ticket prices are as follows: Children (age <= 12): Rs. 5 before 6 PM, Rs. 8 after 6 PM Adults (age > 12 and age <= 65): Rs. 10 before 6 PM, Rs. 12 after 6 PM Seniors (age > 65): Rs. 8 for all show times. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 35/67
  • 39. Multi-way Branching: Excercise III Use of if-else-iflader Statements WAP that calculates the total price for items in an online shopping cart. Apply discounts based on the total purchase amount as follows: 10% discount for purchases above Rs. 100 but less than Rs. 200. 15% discount for purchases above Rs. 200 but less than Rs. 500. 20% discount for purchases of Rs. 500 or more. WAP to compute the electric bill based on the specifications provided in your household electricity bill. The bill includes both fixed charges and variable charges, with the variable charges dependent on the number of units consumed. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 36/67
  • 40. Predict the output (if-else) I Brainstorming Session Continues . . . Snipet 1 int x = 10; if (x > 5) { if (x < 15) { System.out.println("x is between 5 and 15"); } else { System.out.println("x is greater than or equal to 15"); } } else { System.out.println("x is less than or equal to 5"); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 37/67
  • 41. Predict the output (if-else) II Brainstorming Session Continues . . . Snipet 2 int age = 20; if (age >= 18) { System.out.println("You are an adult."); } else if (age >= 13) { System.out.println("You are a teenager."); } else { System.out.println("You are a child."); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 38/67
  • 42. Predict the output (if-else) III Brainstorming Session Continues . . . Snipet 3 int num = 7; if (num % 2 == 0) { System.out.println("Even"); } else if (num % 3 == 0) { System.out.println("Divisible by 3 but not even"); } else { System.out.println("Not even or divisible by 3"); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 39/67
  • 43. Predict the output (if-else) IV Brainstorming Session Continues . . . Snipet 4 int a = 10, b = 20, c = 30; if (a > b && a > c) { System.out.println("a is the largest number."); } else if (b > a && b > c) { System.out.println("b is the largest number."); } else { System.out.println("c is the largest number."); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 40/67
  • 44. Predict the output (if-else) V Brainstorming Session Continues . . . Snipet 5 int num = 10; if (num > 0) { if (num % 2 == 0) { System.out.println("Positive even number."); } else { System.out.println("Positive odd number."); } } else { System.out.println("Not a positive number."); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 41/67
  • 45. Predict the output (if-else) VI Brainstorming Session Continues . . . Snipet 6 int marks = 85; if (marks >= 90) { System.out.println("Grade A"); } else if (marks >= 80) { System.out.println("Grade B"); } else if (marks >= 70) { System.out.println("Grade C"); } else { System.out.println("Grade D"); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 42/67
  • 46. Predict the output (if-else) VII Brainstorming Session Continues . . . Snipet 7 int num = 10; if (num > 0) { if (num % 2 == 0) { System.out.println("Positive even number."); } else { System.out.println("Positive odd number."); } } else if (num < 0) { System.out.println("Negative number."); } else { System.out.println("Zero."); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 43/67
  • 47. Predict the output (if-else) VIII Brainstorming Session Continues . . . Snipet 8 int num = 5; if (num > 0) { if (num < 10) { System.out.println("Single digit positive number."); } else { System.out.println("Positive number, but not single digit." } } else { System.out.println("Non-positive number."); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 44/67
  • 48. Predict the output (if-else) IX Brainstorming Session Continues . . . Snipet 9 int x = 5, y = 10; if (x > 0) { if (y > 0) { System.out.println("Both x and y are positive."); } else { System.out.println("x is positive but y is not."); } } else { System.out.println("x is not positive."); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 45/67
  • 49. Predict the output (if-else) X Brainstorming Session Continues . . . Snipet 10 int a = 10, b = 20, c = 30; if (a > b) { if (a > c) { System.out.println("a is the largest number."); } else { System.out.println("c is the largest number."); } } else { if (b > c) { System.out.println("b is the largest number."); } else { System.out.println("c is the largest number."); } } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 46/67
  • 50. Multi-way Branching: switch-case The switch-casestatement is used to perform different actions based on the value of a variable or expression. It provides a cleaner and more efficient alternative to long if-else-ifchains when dealing with multiple options. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 47/67
  • 51. switch-caseStatement Syntax Synta x switch (<control-var>) { case <value1>: // code block 1 case <value2>: // code block 2 case <value3>: // code block 3 // more cases... [default: // default code block] } Only supports int, char, string, enum data types for control variable Does not support double data type Checks only for equality (==) execute code block if control variable equals(==) case Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 48/67
  • 52. switch-caseFall Through is switch-caseincompleted Without breakstatement? Senari o int x = 3; switch (x) { case 1: System.out.print("1"); case 3: System.out.print("3"); case 5: System.out.print("5"); case 7: System.out.print("7"); default: System.out.print("No Match"); } Outpu t The output will be: 357No Match When control variable matches with a case value rest of the cases are ignored and all the statements are executed breakis used to resolve the problem Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 49/67
  • 53. switch-casewith breakStatement Syntax Synta x switch (<control-var>) { case <value1>: // code block 1 break; case <value2>: // code block 2 break; case <value3>: // code block 3 break; // more cases with break... [default: // default code block] } When control variable matches with a case value only the statements associated with the case block is executed. breakstatement is used to exit the switch statement to end of switch statement. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 50/67
  • 54. switch-casewith breakStatement Example 1 char grade = 'B'; switch (grade) { case 'A': System.out.println("Excellent!"); break; case 'B': System.out.println("Great job!"); break; case 'C': System.out.println("Well done."); break; case 'D': System.out.println("Youpassed."); break; case 'F': System.out.println("Better try again."); break; default: System.out.println("Invalid grade."); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 51/67
  • 55. switch-casewith breakStatement Example 2 int choice = 2; switch (choice) { case 1: System.out.println("You ordered a Cappuccino."); break; case 2: System.out.println("You ordered an Espresso."); break; case 3: System.out.println("You ordered a Latte."); break; default: System.out.println("Invalid menu selection."); } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 52/67
  • 56. Menu Driven Programming I switch-casewith breakStatement: Example 3 using java.util.Scanner; class TempConversion{ public static void main(String args[]){ Scanner input = new Scanner (System.in); System.out.println("Enter 1 for Celsius to Fahrenheit"); System.out.println("Enter 2 for Fahrenheit to Celsius"); System.out.println("Enter your choice: "); int choice = input.nextInt(); double tempInput, tempOutput; switch (choice) { case 1: System.out.print("Enter Temperature in Celsius: "); tempInput = input.nextDouble(); tempOutput = (tempInput * 9 / 5) + 32; System.out.println(tempInput + " oC is equal to " + tempOutput + " oF."); break; Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 53/67
  • 57. Menu Driven Programming II switch-casewith breakStatement: Example 3 case 2: System.out.print("Enter Temperature in Fahrenheit: "); tempInput = input.nextDouble(); tempOutput = (tempInput - 32) * 5 / 9; System.out.println(tempInput + " oC is equal to " + tempOutput + " oF."); break; default: System.out.println("Invalid menu selection."); } } } Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 54/67
  • 58. Brainstorming Session: Fill in the Blanks switch-case 1 In Java, the switch statement is used to perform different actions based on the value of a . 2 The default case in a switch statement is executed if none of the other match the value of the expression. 3 The break statement in a switch statement is used to exit the switch block and prevents . 4 If a break statement is omitted in a case block, control will fall through to the next block. 5 The switch statement is considered an alternative to long chain s when dealing with multiple options. 6 The default case in a switch statement is . Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 55/67
  • 59. Brainstorming Session: Fill in the Blanks switch-case 1 In Java, the switch statement is used to perform different actions based on the value of a control variable . 2 The default case in a switch statement is executed if none of the other cases match the value of the expression. 3 The break statement in a switch statement is used to exit the switch block and prevents fall-through . 4 If a break statement is omitted in a case block, control will fall through to the next case block. 5 The switch statement is considered an alternative to long if- else chains when dealing with multiple options. 6 The default case in a switch statement is optional . Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 56/67
  • 60. switch-case: Excercise I Calculator Program: Write a Java program to implement a simple calculator that performs addition, subtraction, multiplication, and division based on the user’s choice using a switch-case statement. Grade Calculator: Develop a Java program that takes a student’s score as input and prints out their corresponding grade (A, B, C, D, F) based on the score using a switch-case statement. Month Name: Create a Java program that takes an integer representing a month (1 for January, 2 for February, etc.) as input and prints out the name of the month using a switch-case statement. Day of the Week: Write a Java program that takes an integer representing a day of the week (1 for Monday, 2 for Tuesday, etc.) as input and prints out the name of the day using a switch-case statement. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 57/67
  • 61. switch-case: Excercise II Simple ATM Machine: Develop a Java program to simulate a simple ATM machine. The program should allow users to perform operations such as checking balance, withdrawing money, and depositing money using switch-case statements for menu options. Traffic Light Simulator: Write a Java program to simulate a traffic light. The program should take an integer representing the current state of the traffic light (1 for red, 2 for yellow, 3 for green) as input and print out the corresponding action (stop, slow down, go) using a switch- case statement. Simple Menu Driven System: Create a Java program that implements a simple menu-driven system. The program should display a menu with options such as add, delete, update, and exit. Implement each option using switch-case statements. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 58/67
  • 62. switch-case: Excercise III Language Selector: Develop a Java program that takes an integer representing a language (1 for English, 2 for Spanish, 3 for French, etc.) as input and prints out a greeting message in the selected language using switch-case statements. Season Identifier: Write a Java program that takes an integer representing a month (1 for January, 2 for February, etc.) as input and prints out the corresponding season (spring, summer, fall, winter) using a switch-case statement. Simple Game: Develop a Java program for a simple game where the user guesses a number between 1 and 10. The program should generate a random number and compare it with the user’s guess. Provide feedback using switch-case statements to indicate if the guess was too high, too low, or correct. Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 59/67
  • 63. Predict the output (switch-case) I Brainstorming Session Continues . . . Snipet 1 int x = 3; String result; switch (x) { case 1: case 2: result = "One or Two"; break; case 3: case 4: result = "Three or Four"; break; default: result = "Other"; } System.out.println(result); Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 60/67
  • 64. Predict the output (switch-case) II Brainstorming Session Continues . . . Snipet 2 int day = 7; String dayOfWeek; switch (day) { case 1: dayOfWeek = "Monday"; break; case 2: dayOfWeek = "Tuesday"; break; case 3: dayOfWeek = "Wednesday"; break; case 4: dayOfWeek = "Thursday"; break; case 5: dayOfWeek = "Friday"; break; default: dayOfWeek = "Weekend"; } System.out.println(dayOfWeek); Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 61/67
  • 65. Predict the output (switch-case) III Brainstorming Session Continues . . . Snipet 3 char grade = 'B'; String message; switch (grade) { case 'A': message = "Excellent!"; break; case 'B': message = "Good!"; break; case 'C': message = "Average"; break; default: message = "Need Improvement"; } System.out.println(message); Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 62/67
  • 66. Predict the output (switch-case) IV Brainstorming Session Continues . . . Snipet 4 int month = 9; String season; switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Autumn"; break; default: season = "Invalid month"; } System.out.println(season); Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 63/67
  • 67. Predict the output (switch-case) V Brainstorming Session Continues . . . Snipet 5 int num = 10; String result; switch (num % 2) { case 0: result = "Even"; break; case 1: result = "Odd"; break; default: result = "Not an integer"; } System.out.println(result); Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 64/67
  • 68. Predict the output (switch-case) VI Brainstorming Session Continues . . . Snipet 6 int marks = 75; String grade; switch (marks / 10) { case 10: case 9: grade = "A"; break; case 8: grade = "B"; break; case 7: grade = "C"; break; case 6: grade = "D"; break; default: grade = "F"; } System.out.println(grade); Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 65/67
  • 69. Predict the output (switch-case) VII Brainstorming Session Continues . . . Snipet 7 int month = 2; int year = 2024; int days; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) days = 29; else days = 28; break; default: days = -1; } System.out.println("Number of days: " + days); Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 66/67
  • 70. Session 2 Session 2 will be continued with loop structures in java Dr. Meenu & Dr. Riman Mandal & Shamim Java Programming Java Control Structure 67/67