0% found this document useful (0 votes)
7 views

Lec_5.

The document provides an overview of control statements in Java, detailing their purpose in controlling the flow of execution based on conditions. It covers decision-making statements such as if, if-else, and switch, as well as looping statements like for, while, and do-while, including examples for each. Additionally, it includes practice questions and a sample program for a pizza shop that allows customers to place orders and calculate costs.

Uploaded by

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

Lec_5.

The document provides an overview of control statements in Java, detailing their purpose in controlling the flow of execution based on conditions. It covers decision-making statements such as if, if-else, and switch, as well as looping statements like for, while, and do-while, including examples for each. Additionally, it includes practice questions and a sample program for a pizza shop that allows customers to place orders and calculate costs.

Uploaded by

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

Control Statements

Control statements
• Control statements in Java are used to control the
flow of execution based on certain conditions. These
statements can alter the execution sequence, make
decisions, repeat blocks of code, or break out of
loops. The main types of control statements in Java
are:
• 1. Decision-Making Statements
• 2. Looping Statements
Decision-Making Statements

• Decision-making statements are used to execute certain


parts of a program based on specific conditions. Java
provides several types of decision-making statements:
• 1. if Statement
• The if statement evaluates a condition and executes a
block of code if the condition is true.
• Syntax –
if (condition) {
// code to be executed if the condition is true
}
• Example –
public class Main {
public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("Number is greater
than 5");
}
}
}
• 2. if-else Statement
• The if-else statement executes one block of
code if the condition is true and another block
if the condition is false.
• Syntax-
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
• Example –
public class Main {
public static void main(String[] args) {
int number = 3;
if (number > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is not greater than
5");
}
}
}
• 3. if-else-if Ladder
• The if-else-if ladder checks multiple conditions in
sequence. The first condition that evaluates to true will
execute its corresponding block.
• Syntax-
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if all conditions are false
}
• Example-
public class Main {
public static void main(String[] args) {
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");
}
}
}
• 4. switch Statement
• The switch statement selects one of many blocks of code to execute
based on the value of a variable or expression.

• Syntax –
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
default:
// Code to execute if no cases match
}
Example –
public class Main {
public static void main(String[] args) {
int day = 3;

switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other Day");
}
}
}
2. Looping Statements

• 1. for Loop
• The for loop is used when the number of
iterations is known beforehand.
• Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example –
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}
• 2 - while Loop
• The while loop executes the block of code as
long as the condition is true.
• Syntax:
while (condition) {
// Code to execute
}
• Example –
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
}
}
• 3 - do-while Loop
• The do-while loop executes the block of code
at least once, even if the condition is false.
• Syntax:
do {
// Code to execute
} while (condition);
• Example –
public class Main {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
}
}
• break Statement
• The break statement is used to exit a loop prematurely.
• Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop
}
System.out.println("Number: " + i);
}
}
}
• continue Statement
• The continue statement skips the current iteration and
moves to the next.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip this iteration
}
System.out.println("Number: " + i);
}
}
}
• Enhanced for Loop (for-each)
• The enhanced for loop is used to iterate over
arrays or collections.
• Syntax:
• for (type variable : collection/array) {
• // Code to execute
• }
• Example-
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number);
}
}
}
• Practice Questions –
• Grading System:
Write a Java program to accept marks of a student and display their grade based on
the following criteria:
• Marks >= 90: Grade A
• Marks >= 75 and < 90: Grade B
• Marks >= 50 and < 75: Grade C
• Marks < 50: Fail
• Leap Year Check:
Write a program to check if a given year is a leap year. (Hint: A year is a leap year if it
is divisible by 4, but not divisible by 100, except when it is also divisible by 400.)
• Odd or Even:
Write a program to check whether a given number is odd or even using conditional
statements.
• Number Classification:
Accept a number from the user and check whether it is positive, negative, or zero.
• Triangle Validity:
Write a program to check if three given sides can form a valid triangle. (Hint: The
sum of any two sides of a triangle must be greater than the third side.)
• Questions Based on Loops
• Prime Number Check:
Write a program to check if a given number is prime. (Hint: A number is prime if it is
divisible only by 1 and itself.)
• Factorial Calculation:
Write a program to calculate the factorial of a number using a for loop.
• Multiplication Table:
Write a program to generate and display the multiplication table of a number entered by
the user.
• Fibonacci Series:
Write a program to print the first n terms of the Fibonacci series, where n is entered by
the user.
• Number Pattern:
Write a program to generate the following number pattern using nested loops for n
rows:
1
12
123
1234
12345
• Write a program to check whether a given number is a palindrome (e.g., 121, 1331 are
palindromes, but 123 is not).
public class Main {
public static void main(String[] args) {
int num = 121, reversed = 0, temp = num;

// Reverse the number


while (temp > 0) {
int digit = temp % 10;
reversed = reversed * 10 + digit;
temp /= 10;
}

// Check if original and reversed numbers are equal


if (num == reversed) {
System.out.println(num + " is a palindrome.");
} else {
System.out.println(num + " is not a palindrome.");
}
}
}
• Write a program to check if a number is an Armstrong number. (e.g., 153 = 1³ + 5³ + 3³).
public class Main {
public static void main(String[] args) {
int num = 153, sum = 0, temp = num;

while (temp > 0) {


int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}

if (sum == num) {
System.out.println(num + " is an Armstrong number.");
} else {
System.out.println(num + " is not an Armstrong number.");
}
}
}
• Write a program to find the greatest common divisor (GCD) of two
numbers using loops.
public class Main {
public static void main(String[] args) {
int num1 = 56, num2 = 98, gcd = 1;

for (int i = 1; i <= num1 && i <= num2; i++) {


if (num1 % i == 0 && num2 % i == 0) {
gcd = i;
}
}

System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
}
}
• Write a program to find all prime numbers between 1 and 100.
public class Main {
public static void main(String[] args) {
for (int num = 2; num <= 100; num++) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
}
}
• Print the following number pyramid for n = 5:
1
121
12321
1234321
123454321
public class Main {
public static void main(String[] args) {
int n = 5;

for (int i = 1; i <= n; i++) {


// Print spaces
for (int j = n; j > i; j--) {
System.out.print(" ");
}
// Print increasing numbers
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
// Print decreasing numbers
for (int j = i - 1; j >= 1; j--) {
System.out.print(j);
}
System.out.println();
}
}
}
Write a program to convert a binary number to its decimal equivalent.
public class Main {
public static void main(String[] args) {
int binary = 1011, decimal = 0, power = 0;

while (binary > 0) {


int digit = binary % 10;
decimal += digit * Math.pow(2, power);
power++;
binary /= 10;
}

System.out.println("Decimal equivalent: " + decimal);


}
}
Decimal to binary –
import java.util.Scanner;

public class DecimalToBinary {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input: Decimal number


System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();
int temp = decimal;

// Variable to store binary equivalent


String binary = "";

// Convert decimal to binary


while (temp > 0) {
int remainder = temp % 2;
binary = remainder + binary; // Add remainder to the left of the binary string
temp /= 2; // Divide by 2
}

// Output: Binary equivalent


System.out.println("Binary equivalent of " + decimal + " is: " + binary);
}
}
• Objective:
• Design a menu-driven program for a pizza shop that allows customers to place an order, select different pizzas, sizes, and toppings, and calculates the
total cost of the order. The program should also provide an option for the customer to place multiple orders in a single session.
• Requirements:
• Pizza Menu:
– The customer should be able to choose from the following pizza types:
• Margherita - $8
• Pepperoni - $10
• Veggie - $9
• BBQ Chicken - $12
• Pizza Size:
– After selecting the pizza type, the customer can choose the size of the pizza:
• Small - $2
• Medium - $4
• Large - $6
• Toppings:
– The customer can select multiple toppings from the following options:
• Cheese - $1
• Olives - $1.5
• Mushrooms - $2
• Bacon - $3
– The customer can choose to stop adding toppings by selecting "No more toppings."
• Order Calculation:
– The program should calculate the total cost based on the pizza type, size, and toppings selected.
– Display the final total cost of the order after all selections are made.
• Order Summary:
– After the order is placed, the system should display the total amount due.
– The system should prompt the user if they wish to place another order or exit.
• Program Flow:
– The program should run until the customer chooses to exit.
– Each customer’s order should be processed separately, and the total amount should be calculated and displayed after each order.
– The program should allow for multiple orders in a session.
• Functionalities:
• Display the pizza menu with options for the customer to choose from.
• Allow the customer to select the size and toppings for the pizza.
• Calculate the total price based on selected pizza, size, and toppings.
• Display the total cost and ask if the customer wants to order more or exit.
Sample input and output-
Enter your choice (1-5): 2
You selected Pepperoni Pizza.

Select the size of your pizza:


1. Small - $2
2. Medium - $4
3. Large - $6
Enter your choice (1-3): 3
You selected Large size.

Do you want to add toppings?


1. Cheese - $1
2. Olives - $1.5
3. Mushrooms - $2
4. Bacon - $3
5. No more toppings
Enter your topping choice (1-5): 1
You added Cheese.

Enter your topping choice (1-5): 4


You added Bacon.

Your total cost is: $21.00

Would you like to order another pizza?


1. Yes
2. No
Enter your choice (1-2): 2
Thank you for your order!
• Constraints:
• The customer should only be able to select
valid choices from the menu. Invalid choices
should be handled properly.
• The program should not allow negative or zero
values for any price component.
• The program should continue running until
the customer explicitly chooses to exit.
import java.util.Scanner;

public class PizzaShop {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Variables for customer order


int pizzaChoice = 0, sizeChoice = 0, toppingChoice = 0;
double pizzaPrice = 0, sizePrice = 0, toppingPrice = 0, totalCost = 0;
boolean addMoreToppings = true;

// Display Pizza Menu


System.out.println("Welcome to the Pizza Shop!");
while (true) {
System.out.println("\nSelect your pizza:");
System.out.println("1. Margherita - $8");
System.out.println("2. Pepperoni - $10");
System.out.println("3. Veggie - $9");
System.out.println("4. BBQ Chicken - $12");
System.out.println("5. Exit");

System.out.print("Enter your choice (1-5): ");


pizzaChoice = scanner.nextInt();

if (pizzaChoice == 5) {
System.out.println("Thank you for visiting Pizza Shop!");
break; // Exit the program
}
switch (pizzaChoice) {
case 1:
pizzaPrice = 8;
System.out.println("You selected Margherita Pizza.");
break;
case 2:
pizzaPrice = 10;
System.out.println("You selected Pepperoni Pizza.");
break;
case 3:
pizzaPrice = 9;
System.out.println("You selected Veggie Pizza.");
break;
case 4:
pizzaPrice = 12;
System.out.println("You selected BBQ Chicken Pizza.");
break;
default:
System.out.println("Invalid choice! Please select again.");
continue;
}

// Size Choice
System.out.println("\nSelect the size of your pizza:");
System.out.println("1. Small - $2");
System.out.println("2. Medium - $4");
System.out.println("3. Large - $6");

System.out.print("Enter your choice (1-3): ");


sizeChoice = scanner.nextInt();
switch (sizeChoice) {
case 1:
sizePrice = 2;
System.out.println("You selected Small size.");
break;
case 2:
sizePrice = 4;
System.out.println("You selected Medium size.");
break;
case 3:
sizePrice = 6;
System.out.println("You selected Large size.");
break;
default:
System.out.println("Invalid choice! Please select again.");
continue;
}

// Toppings choice loop


totalCost = pizzaPrice + sizePrice;
while (addMoreToppings) {
System.out.println("\nDo you want to add toppings?");
System.out.println("1. Cheese - $1");
System.out.println("2. Olives - $1.5");
System.out.println("3. Mushrooms - $2");
System.out.println("4. Bacon - $3");
System.out.println("5. No more toppings");

System.out.print("Enter your topping choice (1-5): ");


toppingChoice = scanner.nextInt();
switch (toppingChoice) {
case 1:
toppingPrice = 1;
System.out.println("You added Cheese.");
break;
case 2:
toppingPrice = 1.5;
System.out.println("You added Olives.");
break;
case 3:
toppingPrice = 2;
System.out.println("You added Mushrooms.");
break;
case 4:
toppingPrice = 3;
System.out.println("You added Bacon.");
break;
case 5:
addMoreToppings = false;
System.out.println("No more toppings added.");
break;
default:
System.out.println("Invalid choice! Please select again.");
continue;
}

totalCost += toppingPrice;
}
// Final total
System.out.printf("\nYour total cost is: $%.2f\n", totalCost);

// Ask if the customer wants to order another pizza


System.out.println("\nWould you like to order another pizza?");
System.out.println("1. Yes");
System.out.println("2. No");
System.out.print("Enter your choice (1-2): ");
int orderAgain = scanner.nextInt();
if (orderAgain == 2) {
System.out.println("Thank you for your order!");
break;
} else {
addMoreToppings = true; // Reset topping choice for next order
}
}
}
}

You might also like