# Control Structures

## Make a Decision: If-Statement

Patrick 🐥 is a very polite duck who likes to greet everyone he meets with “Good Morning,” “Good Afternoon,” or “Good Night” depending on the current time.

(image by National Geographic: giphy.com/natgeochannel)

As we learned before, we can print these statements as below:

System.out.println("Good Morning");   // say it between 0:00 - 11:59
System.out.println("Good Afternoon"); // say it between 12:00 - 19:59
System.out.println("Good Night");     // say it between 20:00 - 23:59


However, we also know Patrick 🐥 should only decide to say one of these statements based on the current time.

In other words, we need to write code that makes a decision on what to print based on the conditions of the situation (conditionally).

In Java, we make a decision by using an if statement or an if…else statement. Read the notes below:

Let’s revisit the greating example above, and make decision for Patrick on whether to say “Good Morning,” “Good Afternoon,” “Good Night”.

Patrick should say “Good Morning” between 0:00 - 11:59, “Good Afternoon” between 12:00 - 19:59, and “Good Night” between 20:00 - 23:59.

1. We have a variable currentHour that stores the current hour.
2. Fill out the correct boolean expression A and boolean expression B to complete the program.
3. Test your result by assigning the variable currentHour to numbers from 0 to 23:

## Repeat It Again: For-Loop, While-Loop

In math class, Patrick’s 🐥 teacher ask the class to solve a math challenge, and he might need some help.

The teacher asks them to find the sum of 1, 2, 3, …., 100. That is what is 1 + 2 + 3 + 4 … + 99 + 100?

While we can plug this into a calculator, that is gonna take a while. Thankfully, in Java, you can easily calculate this in 3 lines with the help of a for loop or while loop.

After learning about for loop and while loop, let’s see how do we help Patrick 🐥 and calculate 1 + 2 + 3 + 4 … + 99 + 100 easily?

Let’s try to do it in a while loop:

1. We have a variable called total that tracks the total addition sum we get so far.
2. We have a variable called num that tracks the next number to be added to total.
3. Write out the appropriate boolean expression and write out the while loop.

By following those step we will get a while loop like this:

int total = 0;
int num = 1;
while(num <= 100){
total = total + num;
num = num + 1;
}
System.out.println("Answer calculated in a while loop: " + total);


Test this out below by clicking Run and write a for loop version that calculates the same thing! You should get the same answer!