Conditionals and Loops

 

Chapter: 10

Conditional Statements


Decision Making


Conditional statements are used to perform different actions based on different conditions.
The if statement is one of the most frequently used conditional statements.
If the if statement's condition expression evaluates to true, the block of code inside the if statement is executed. If the expression is found to be false, the first set of code after the end of the if statement (after the closing curly brace) is executed.
Syntax:
if (condition) {
//Executes when the condition is true
}
JAVA
Any of the following comparison operators may be used to form the condition:
less than
greater than
!= not equal to
== equal to
<= less than or equal to
>= greater than or equal to

For example:
int x = 7;
if(x < 42) {
System.out.println("Hi");
}
JAVA
Remember that you need to use two equal signs (==) to test for equality, since a single equal sign is the assignment operator.

Decision Making

Fill in the blanks to print "Yeah".

int x = 5;

( x == 5 ) {

System.
.println("Yeah");

}

if...else Statements


An if statement can be followed by an optional else statement, which executes when the condition evaluates to false.
For example:
int age = 30;

if ​(age < 16) {
​System.out.println("Too Young");
} else {
​System.out.println("Welcome!");
}
JAVA
As age equals 30, the condition in the if statement evaluates to false and the else statement is executed.

if...else Statements

Fill in the blanks to print the greater number.

int x = 10; int y = 5;

( x > y ) {

System.out.println(
);

}

{

System.out.println(y);

}

Chapter: 11

Nested if Statement


Nested if Statements

You can use one if-else statement inside another if or else statement.
For example:
int age = 25;
if(age > 0) {
if(age > 16) {
System.out.println("Welcome!");
} else {
System.out.println("Too Young");
}
} else {
System.out.println("Error");
}
JAVA
You can nest as many if-else statements as you want.


Nested if Statements

Please fill in the missing parts of the nested if statement to print "it works!" to the screen.

int x = 37;

if (x > 22) {

(x > 31) {

System.
.println("it works!");

}

}

Chapter: 12

Else if Statement


else if Statements


Instead of using nested if-else statements, you can use the else if statement to check multiple conditions.
For example:
int age = 25;

if(age <= 0) {
System.out.println("Error");
} else if(age <= 16) {
System.out.println("Too Young");
} else if(age < 100) {
System.out.println("Welcome!");
} else {
System.out.println("Really?");
}
JAVA
The code will check the condition to evaluate to true and execute the statements inside that block.
You can include as many else if statements as you need.

else if Statements

An if statement can contain how many else if statements?

None
As many as you want
Only two

Chapter: 13

Logical Statements


Logical Operators


Logical operators are used to combine multiple conditions.

Let's say you wanted your program to output "Welcome!" only when the variable age is greater than 18 and the variable money is greater than 500.
One way to accomplish this is to use nested if statements:
if (age > 18) {
if (money > 500) {
System.out.println("Welcome!");
}
}
JAVA
However, using the AND logical operator (&&) is a better way:
if (age > 18 && money > 500) {
System.out.println("Welcome!");
}
JAVA
If both operands of the AND operator are true, then the condition becomes true.

Logical Operators

Fill in the blank to test both conditions in the following if statement.

int age = 23;

int money = 4000;

if (age > 21
money > 500) {

System.out.println("Welcome");

}


The OR Operator


The OR operator (||) checks if any one of the conditions is true.
The condition becomes true, if any one of the operands evaluates to true.
For example:
int age = 25;
int money = 100;

if (age > 18 || money > 500) {
System.out.println("Welcome!");
}
JAVA
The code above will print "Welcome!" if age is greater than 18 or if money is greater than 500.

The NOT !) logical operator is used to reverse the logical state of its operand. If a condition is true, the NOT logical operator will make it false.
Example:
int age = 25;
if(!(age > 18)) {
System.out.println("Too Young");
} else {
System.out.println("Welcome");
}
JAVA
!(age > 18) reads as "if age is NOT greater than 18".

The OR Operator

What is the output of the following code? int a = 11; int b = 12; int c = 40; if (a > 100 || b > 3) { System.out.println(a); } else { System.out.println(c); }



Chapter: 14

The Switch Statement


The switch Statement


switch statement tests a variable for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
Syntax:
switch (expression) {
case value1 :
//Statements
break; //optional
case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
JAVA
- When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
- When a break statement is reached, the switch terminates, and the flow of control jumps to the next line after the switch statement.
- Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

The example below tests day against a set of values and prints a corresponding message.
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;
}
JAVA
You can have any number of case statements within a switch. Each case is followed by the comparison value and a colon.

Fill in the blanks to test the variable's value using the switch statement.

int x = 10;

(
) {

case 10:

System.out.println("A");

break;

20:

System.out.println("B");

break;

}

The default Statement


A switch statement can have an optional default case.
The default case can be used for performing a task when none of the cases is matched.

For example:
int day = 3;

switch(day) {
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Weekday");
}
JAVA
No break is needed in the default case, as it is always the last statement in the switch.

The default Statement

What is the output of the following code? int a = 11; int b = 12; int c = 40; switch (a) { case 40: System.out.println(b); break; default: System.out.println(c); }


The switch Expression


The switch expression allows multiple comma-separated values per case and returns a value for the whole switch-case block.

For example:
String dayType = switch(day) {
case 1, 2, 3, 4, 5 -> "Working day";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};
JAVA
The switch expression makes the switch-case block much shorter and doesn't use a break statement.
Notice the -> shorthand after the cases.

The switch Expression

Fill in the blanks to create a valid switch expression for coffee price.

int price =
(coffee) {

case "Espresso", "Americano"
15;

case "Latte", "Macchiato"
20;

default -> 0;

};

Practice:

The switch Statement



Your robot can recognize your emotions marked with number that represents each of them:
1 - You are happy!
2 - You are sad!
3 - You are angry!
4 - You are surprised!
Write a program that takes the emotion number as input and outputs the corresponding message in given format.
If the input is an emotion that the program doesn’t know, it should output: "Unknown emotion.".

Sample input
1

Sample output
You are happy!
Don't forget about the break statement.

Chapter: 15

While Loop


while Loops


loop statement allows to repeatedly execute a statement or group of statements.

while loop statement repeatedly executes a target statement as long as a given condition is true.

Example:
int x = 3;

while(x > 0) {
System.out.println(x);
x--;
}
JAVA
The while loops check for the condition x > 0. If it evaluates to true, it executes the statements within its body. Then it checks for the statement again and repeats.
Notice the statement x--. This decrements x each time the loop runs, and makes the loop stop when x reaches 0.
Without the statement, the loop would run forever.

while Loops

Rearrange the code to produce a valid finite loop which prints a text to the screen in the loop.

int x = 12;
while (x < 100) {
System.out.println("Java rocks!");
x++; }

while Loops



When the expression is tested and the result is false, the loop body is skipped and the first statement after the while loop is executed.
Example:
int x = 6;

while( x < 10 )
{
System.out.println(x);
x++;
}
System.out.println("Loop ended");

/*
6
7
8
9
Loop ended
*/
JAVA
Notice that the last print method is out of the while scope.

while Loops

How many times will the following loop work? int x = 0; int y = 5; while (x < y) { System.out.println("Hello"); x++; }


Chapter: 16 

For Loop


for Loops


Another loop structure is the for loop. A for loop allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax:
for (initialization; condition; increment/decrement) {
statement(s)
}
JAVA
Initialization: Expression executes only once during the beginning of loop
Condition: Is evaluated each time the loop iterates. The loop executes the statement repeatedly, until this condition returns false.
Increment/Decrement: Executes after each iteration of the loop.

The following example prints the numbers 1 through 5.
for(int x = 1; x <=5; x++) {
System.out.println(x);
}
JAVA
This initializes x to the value 1, and repeatedly prints the value of x, until the condition x<=5 becomes false. On each iteration, the statement x++ is executed, incrementing x by one.
Notice the semicolon (;) after initialization and condition in the syntax.

for Loops

Drag and drop from the options below to print "Great!" 10 times:

for

(int i = 0; i < 10;

i++

) {


System.out.println("

Great!

");


}


for Loops


You can have any type of condition and any type of increment statements in the for loop.
The example below prints only the even values between 0 and 10:
for(int x=0; x<=10; x=x+2) {
System.out.println(x);
}
/*
0
2
4
6
8
10
*/
JAVA
for loop is best when the starting and ending numbers are known.

for Loops

How many times will the following loop run? for (int i = 2; i < 10; i = i*i) { System.out.println(i); }


Chapter: 17

Do While Loop


do...while Loops


do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
Example:
int x = 1;
do {
System.out.println(x);
x++;
} while(x < 5);

/*
1
2
3
4
*/
JAVA
Notice that the condition appears at the end of the loop, so the statements in the loop execute once before it is tested.
Even with a false condition, the code will run once.
Example:
int x = 1;
do {
System.out.println(x);
x++;
} while(x < 0);
JAVA
Notice that in do…while loops, the while is just the condition and doesn't have a body itself.

do...while Loops

How is a do while loop different from a while loop?

A do while loop tests the condition before running the code.
A while loop runs the code before testing the condition.
A do while loop runs your code at least one time.

Loop Control Statements


The break and continue statements change the loop's execution flow.
The break statement terminates the loop and transfers execution to the statement immediately following the loop.
Example:
int x = 1;

while(x > 0) {
System.out.println(x);
if(x == 4) {
break;
}
x++;
}
JAVA
The continue statement causes the loop to skip the remainder of its body and then immediately retest its condition prior to reiterating. In other words, it makes the loop skip to its next iteration.
Example:
for(int x=10; x<=40; x=x+10) {
if(x == 30) {
continue;
}
System.out.println(x);
}
JAVA
As you can see, the above code skips the value of 30, as directed by the continue statement.

Loop Control Statements

Fill in the blanks to print the values of the x variable 5 times.

int x = 1;

do {

System.out.println(x);

x++;

}

(x <=
);

Chapter: 18

Module 2 Quiz


Fill in the blanks to print "in a loop" 7 times, using the while loop.

int x = 1;

while (x <=
) {

System.out.println("in a loop");

++;

}




Fill in the blanks to print "in a loop" 5 times using the for loop.

(int x = 0;
< 5; x++) {

System.out.println("in a loop");

}

Code Project

Loan Calculator


Loan Calculator


You take a loan from a friend and need to calculate how much you will owe him after 3 months.
You are going to pay him back 10% of the remaining loan amount each month.
Create a program that takes the loan amount as input, calculates and outputs the remaining amount after 3 months.

Sample Input:
20000

Sample Output:
10628

Here is the monthly payment schedule:
Month 1
Payment: 10% of 20000 = 2000
Remaining amount: 18000
Month 2
Payment: 10% of 18000 = 1800
Remaining amount: 16200
Month 3:
Payment: 10% of 16200 = 1620
Remaining amount: 14580.

Note: Comment down your answer after solving the question.
Use a loop to calculate the payment and remaining amounts for each month.
Also, use integers for amounts.


Comments