Programming
Programming
Switch Case
- It is a multi-way branch statement. It provides an easy way to dispatch execution to different parts
of code based on the value of an expression.
- The expression in a switch statement must be of type char, byte, short, int, or String.
Do - While Statement
- It is similar to the while loop, but the condition is tested after the execution of the loop’s body. This
means the loop body will execute at least once.
- The condition is a boolean expression. If it evaluates to true, the loop will continue to execute. If it
evaluates to false, the loop will terminate.
While - Do Statement
- The while loop repeatedly executes a block of statements as long as a particular condition is true.
- Similar to the do-while loop, the condition is a boolean expression. The difference is that in a
while loop, the condition is tested before the execution of the loop’s body. If the condition is false
at the start, the loop body will not execute at all.
import java.util.Scanner;
switch (num % 2) {
case 0:
System.out.println("The number is an even number");
break;
case 1:
case -1:
System.out.println("The number is an odd number");
break;
}
}
}
b. Using a switch statement, write a Java program that will perform the operation for the two entered
integers based on the chosen operator of the user.
import java.util.Scanner;
switch (operator) {
case '+':
System.out.println("The result is: " + (num1 + num2));
break;
case '-':
System.out.println("The result is: " + (num1 - num2));
break;
case '*':
System.out.println("The result is: " + (num1 * num2));
break;
case '/':
if (num2 != 0) {
System.out.println("The result is: " + (num1 / (double) num2));
} else {
System.out.println("Error! Dividing by zero is not allowed.");
}
break;
default:
System.out.println("Error! Invalid operator. Please enter correct operator.");
break;
}
}
}
c. Write a program to print all natural numbers from 1 to 10 using while do and do while loop.
import java.util.Scanner;