Safaan Hashmi
Lecture 4 04-Aug-2024
Practice Problems
1. Write a program to demonstrate nested if-else statement
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Age");
int age = sc.nextInt();
System.out.println("Enter Gender (M/F)");
String gender =sc.next();
if(gender.equals("M"))
if(age<18){
System.out.println("Hello Sir, you are not elegible to create account");
else{
System.out.println("Hello Sir, you are elegible to create account");
else{
if(age<18){
System.out.println("Hello Ma'am, you are not elegible to create account");
else{
System.out.println("Hello Ma'am, you are elegible to create account");
}
}
OUTPUT -:
2. Write a program to demonstrate the use of for loop in java.
class LoopsInJava {
public static void main(String[] args) {
System.out.println("For loop");
int n = 5;
for (int i = 1; i <= n; ++i) {
System.out.println("Java is fun");
OUTPUT -:
3. Write a program to demonstrate the use of the Switch Case Statement.
class SwitchCase {
public static void main(String[] args) {
int number = 44;
String size;
switch (number) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
break;
case 44:
size = "Large";
break;
case 48:
size = "Extra Large";
break;
default:
size = "Unknown";
break;
System.out.println("Size: " + size);
}
4. Write a program to demonstrate the use of for each loop.
class ForEach {
public static void main(String[] args) {
System.out.println("For-Each Loop");
int[] numbers = {10, 20, 30, 40};
for (int number: numbers) {
System.out.println(number);
5. Write a program to demonstrate the use of while and do..while loop.
class While {
public static void main(String[] args) {
System.out.println("While loop");
int i=1;
while(i<=5){
System.out.println(i);
i++;
System.out.println("Do-While loop");
int j=1;
do{
System.out.println(j);
j++;
}while(j<=10);