Hello, and welcome to the fourth instalment of the blog series "The DSA Handbook".
In this blog post, we will discuss the different types of conditional statements and loops that are available in Java, and how they can be used to control the flow of a program.
Let's begin now.
Conditional Statements
Conditional statements in Java allow the programmer to execute a specific block of code only if a certain condition is met.
if statement
The most basic form of a conditional statement is the if
statement.
The syntax for an if
statement is as follows:
if (condition) {
// code to execute if condition is true
}
For example, the following code will print "Hello, World!" if the variable x is greater than 0:
int x = 5;
if (x > 0) {
System.out.println("Hello, World!");
}
if-else statement
An if-else
statement allows for different code to be executed depending on whether the condition is true or false.
The syntax for an if-else
statement is as follows:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
For example, the following code will print "x is positive" if the variable x is greater than 0, and "x is non-positive" otherwise:
int x = 5;
if (x > 0) {
System.out.println("x is positive");
} else {
System.out.println("x is non-positive");
}
Nested if-else statement
A nested if-else
statement can be used when there are multiple conditions that need to be checked.
The syntax for a nested if-else
statement is as follows:
if (condition1) {
// Code to be executed if condition1 is true
if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if condition2 is false
}
} else {
// Code to be executed if condition1 is false
}
For example, the following code will print "x is positive and even" if x is greater than 0 and even, "x is positive and odd" if x is greater than 0 and odd, "x is non-positive" otherwise:
int x = 5;
if (x > 0) {
if (x % 2 == 0) {
System.out.println("x is positive and even");
} else {
System.out.println("x is positive and odd");
}
} else {
System.out.println("x is non-positive");
}
Switch-case statements
The switch-case
statement is used when there are multiple cases that need to be checked. It is used to perform different actions based on the value of a variable.
The basic syntax of the switch-case
statement is as follows:
switch (variable) {
case value1:
// code to execute if variable == value1
break;
case value2:
// code to execute if variable == value2
break;
...
default:
// code to execute if variable does not match any case
}
For example, the following code will print "x is 1" if x is 1, "x is 2" if x is 2, and "x is something else" otherwise:
int x = 1;
switch (x) {
case 1:
System.out.println("x is 1");
break;
case 2:
System.out.println("x is 2");
break;
default:
System.out.println("x is something else");
}
Loops
In programming, a loop is a control flow statement that allows code to be executed repeatedly based on a given condition.
There are several types of loops in Java, each with its own specific use case.
For Loop
This type of loop is used to iterate through a range of numbers or an array. It is defined by the keyword "for" followed by parentheses.
The syntax for a for
loop in Java is as follows:
for(initialization; condition; increment/decrement){
//code to be executed
}
Example:
for(int i = 0; i < 10; i++){
System.out.println(i);
}
While Loop
This type of loop is used to repeatedly execute code as long as a given condition is true. It is defined by the keyword "while" followed by parentheses.
The syntax for a while
loop in Java is as follows:
while(condition){
//code to be executed
}
Example:
int i = 0;
while(i < 10){
System.out.println(i);
i++;
}
When you know how many times loop will execute, use 'for loop'
Example: Input numbers upto 10
When you don't know how many times loop will execute, use 'while loop'
Example: Input numbers till user does not press x
Do-While Loop
This type of loop is similar to a while loop, but the code inside the loop is executed at least once, regardless of whether the condition is true or false. It is defined by the keyword "do" followed by the loop code and the keyword "while" followed by parentheses.
The syntax for a do-while
loop in Java is as follows:
do{
//code to be executed
}while(condition);
Example:
int i = 0;
do{
System.out.println(i);
i++;
}while(i < 10);
For-each Loop
This type of loop is used to iterate through an array or a collection. It is defined by the keyword "for" followed by parentheses.
The syntax for an enhanced for
loop in Java is as follows:
for(type variable : array/collection){
//code to be executed
}
Example:
int[] numbers = {1, 2, 3, 4, 5};
for(int number : numbers){
System.out.println(number);
}
It is important to note that using the correct type of loop for a specific task can greatly improve the readability and efficiency of your code. Additionally, it is important to include a way to exit the loop to avoid infinite loops.
Some practice questions
1. Find the largest of three numbers a,b and c
Approach 1 :
int a = 5;
int b = 7;
int c = 9;
int largest = a;
if(b>largest) {
largest = b;
}
if(c>largest) {
largest = c;
}
System.out.print(largest);
Approach 2 :
int a = 5;
int b = 7;
int c = 9;
int largest = Math.max(Math.max(a, b), c);
System.out.println("The largest number among " + a + ", " + b + ", and " + c + " is: " + largest);
This code declares three variables, a
, b
, and c
, and assigns them the values 5, 7, and 9 respectively. Then, it uses the Math.max()
method to find the largest of these three numbers. The Math.max()
method takes two parameters and returns the larger of the two.
The code first calls Math.max(a, b)
which will return the maximum of a and b. Then it calls Math.max(Math.max(a, b), c)
which will return the maximum of maximum of a and b and c.
The result of the Math.max()
method is then stored in the variable largest
. Finally, the code prints out a message displaying the largest number among a, b, and c.
2. Check if the alphabet is upper case or lower case
Scanner input = new Scanner(System.in);
System.out.print("Enter an alphabet: ");
char letter = input.next().trim().charAt(0);
if (letter >= 'A' && letter <= 'Z') {
System.out.println("The alphabet you entered is UPPER CASE.");
} else if (letter >= 'a' && letter <= 'z') {
System.out.println("The alphabet you entered is LOWER CASE.");
} else {
System.out.println("Invalid input. Please enter a single alphabet.");
}
This code prompts the user to enter an alphabet. The next()
method is used to read the input from the user. The trim()
method is used to remove any leading or trailing spaces from the input string. The charAt(0)
method is used to get the first character of the input string, which is the alphabet entered by the user. This character is stored in the variable letter
.
The code then checks if the value of letter
is between 'A' and 'Z' (inclusive) using an if
statement. If it is, it prints "The alphabet you entered is UPPER CASE." If the value of letter
is between 'a' and 'z' (inclusive), it prints "The alphabet you entered is LOWER CASE." Otherwise, it prints "Invalid input. Please enter a single alphabet."
3. Counting Occurences
Count the number of times the digit 7 occurs in a given number 135747377.
int number = 135747377;
int count = 0;
while (number > 0) {
if (number % 10 == 7) {
count++;
}
number = number / 10;
}
System.out.println("The number 7 occurs " + count + " times in " + number);
In this example, the integer variable number
is initialized with the value 135747377. Then, a while loop is used to iterate through each digit of the number. Inside the loop, the modulus (%)
operator is used to get the remainder of the current number when divided by 10, which gives the last digit of the number. A conditional statement is used to check if the last digit is equal to 7. If it is, the count variable is incremented by 1.
After that, the current number is divided by 10 using the division operator (/
) which removes the last digit from the number, and the loop continues until the number is greater than 0.
After the loop, the final count is printed out with a message displaying the number of times 7 occurs in the given number.
So the output of the above code will be :
The number 7 occurs 4 times in 135747377
4. Reverse a Number
int number = 72;
int reversedNumber = 0;
while (number > 0) {
int lastDigit = number % 10;
reversedNumber = reversedNumber * 10 + lastDigit;
number = number / 10;
}
System.out.println("The reversed number is " + reversedNumber);
In this example, the integer variable number
is initialized with the value 72. Then, a while loop is used to iterate through each digit of the number. Inside the loop, the modulus operator is used to get the remainder of the current number when divided by 10, which gives the last digit of the number.
Then the last digit is added to a new variable reversedNumber
by multiplying the current reversedNumber
value by 10 and adding the last digit.
After that, the current number is divided by 10 using the division operator (/
) which removes the last digit from the number, and the loop continues until the number is greater than 0.
After the loop, the final reversed number is printed out.
So the output of the above code will be :
The reversed number is 27
Conclusion
In conclusion, conditional statements and loops are an essential part of programming in Java. They are used to control the flow of a program and to execute a block of code multiple times. Understanding how to use these features can help you to write more efficient and effective Java code.