Control Structures Flashcards

1
Q

What is a boolean expression?

A

A boolean data type can have only two specific values: true or false. Boolean expressions that evaluate to true or false are how we can set up conditions for something to happen; for example, (cost > budget) means you can’t afford something and (myScore > opponentScore) could mean I win the game. These types of condition express a “relation” between two values using a relational operator. Here are the Java relational operators:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How would one compare Strings?

A

You can use these relational operators on the primitive data types- even char! However, they won’t work with String variables. One of the most common Java mistakes by developers is trying to compare two strings using “==”. Instead you have to use String’s .equals method like so:

string1.equals(string2)

This is true if and only if the strings are exactly the same length, and all their characters match exactly. Either or both strings can be a variable. For example, if name contains “John Doe”, all the following expressions are false:

name. equals(“John”); // too short
name. equals(“john doe”); // case doesn’t match name.equals(“John Doe “); // extra space at end name.equals(“John Doe “); // extra space in middle

Here are the most commonly used String comparison methods that result in a boolean value of true or false and an example evaluates to true:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is an “If statement”?

A

Java allows you to choose to only run parts of your code if something is true. This is called an “if statement”. For example let’s say you are writing a shopping program, and if a user is part of a special preferred club- they get a 10% discount on their price. You might write code that looks like this:

if (status.equals(“preferred”)) {

System.out.println(“Preferred discount applied”);

price = price * 0.90;

}

If the boolean expression in the parentheses is true, then Java does all the statements within the curly braces. Otherwise, it skips them and goes on to the next statement. This kind of situation is sometimes called a “simple decision”, or a “do it or not”.

Syntax

if(boolean test) {

//statements

}

The boolean test can be anything you like as long as in the end it evaluates to either “true” or “false”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is an “If/Else” statement?

A

When you use an “if statement” you are limited to only one behavior, either that code runs or it doesn’t. When you need to do two different things depending on whether the condition is true or not, you can add an else statement after the if like this:

if (numberEntered != 12345) {

System.out.println(“You entered the magic number!”);

points = points + 1;

} else {

System.out.println(“Sorry, that’s not right.”);

}

For this “either-or” situation, one and only one of the two blocks of code is always executed: the first block if the condition is true, or the second if it’s false.

Syntax

if(boolean test) {

//statements

} else {

//statements

}

Note that only one of these branches of code will execute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How would you check if a number of different conditions is true?

A

Sometimes you’re checking to see which of a number of different conditions is true. For this, you can sort of combine the else with another if for each separate condition:

if (temperature > 70) {

System.out.println(“No coat required”);

} else if (temperature > 50) {

System.out.println(“Wear a jacket”);

} else if (temperature > 20) {

System.out.println(“Wear a warm coat”);

} else {

System.out.println(“Stay inside!”);

}

In this “multi-way if”, the first block of code whose condition is true is the only one that will be executed. Java looks at each test in order from top to bottom until it either finds one that evaluates to true, or it reaches the else statement. This means the order of the conditions can be very important; the example above would always recommend either a warm coat or staying inside if the order of the conditions was reversed. You should usually include an else at the end to make sure you’ve taken care of the possibility that NONE of the conditions is true, even if all you do is print an error message that an unexpected value was found.

Syntax

if(boolean test 1) {

//statements

} else if (boolean test 2) {

//statements

} else {

//statements

}

Remember that only 1 of these blocks will get executed, and that Java will stop as soon as it executes a block. That means that if you don’t plan the order of your tests properly, or accidentally design them to overlap you might not get the behavior you want. It’s also important to remember that you don’t need a test for the else- it will get run no matter what if everything else if false. It’s a common error to try and give the else a test, but instead you can just leave a comment that indicates in which cases the else code will run.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How would one combine logic?

A

Sometimes you need to combine conditions in different ways. In the card game of poker, for example, a hand can be a straight (5 cards in order), a flush (5 cards of the same suit), or a straight flush (both). Here’s one way to code this, with a second if statement “nested” inside the first one.

if (straight) {

if (flush) {

System.out.println(“straight flush”);

} else {

System.out.println(“straight”);

}

} else if (flush) {

System.out.println(“flush”);

}

We can also use boolean expressions to code this. A straight flush is when a hand is both a straight and a flush; that is, when both straight and flush are true. Java provides three logical operators that combine boolean expressions:

Using boolean expressions, we can simplify the poker example above to:

if (straight && flush) {

System.out.println(“straight flush”);

} else if (straight) {

System.out.println(“straight”);

} else if (flush) {

System.out.println(“flush”);

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How would one use boolean expressions to represent algebraic inequalities?

A

Boolean expressions can be used to represent the classic algebraic inequalities on a number line:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are loops?

A

If you think about it, we must be missing something basic in our study of Java so far. We’ve all experienced our computer being really busy for a long time, and we know it does things really fast. So, even if a game program like Space Invaders was a million lines of code, it would finish executing all those statements in at most a few minutes. But, the game can go on for hours! What’s happening?

As you may have guessed, the computer is executing the same lines of code over and over again. In Space Invaders, it’s updating the positions of all the spaceships, moving your if you pressed the right keys, checking to see if any collisions have occurred, etc. And, it’s doing all of this dozens of times every second. We say it’s “looping”, because once it gets to the last statement, it returns to the first statement and then continues:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a “for loop”?

A

One of the most common usage of loops is when we just want to repeat some lines of code a specific number of times. For example, this tiny tic-tac-toe board repeats the same println four times.

System.out.println(“+-+-+-+”);

System.out.println(“+-+-+-+”);

System.out.println(“+-+-+-+”);

System.out.println(“+-+-+-+”);

output…

+-+-+-+

+-+-+-+

+-+-+-+

+-+-+-+

We said earlier that duplicate lines of code in a program is generally not a good thing, so instead we can use a “for loop” to repeat one line four times like this:

for (int i = 1; i <= 4; i++) {

System.out.println(“+-+-+-+”);

}

Syntax

for (initialization; test; update) {

body

}

The for loop has four distinct parts:

initialization

int i=1 initializes the loop. In this example it defines the integer variable i which the loop will use to count to 4; it’s a “loop counter”. You can use any variable you want here, including one declared previously in the code.

test

i<=4 is the test to determine whether the loop should continue or not. It keeps going as long as this Boolean expression evaluates to true; in this example, while the loop counter is less than or equal to 4. It’s important to know that this test is done at the beginning of the loop, so it’s possible to write a loop that executes zero times!

update

i++ is the update. If a loop that starts is ever going end, something has to change while it’s running change so that the test eventually becomes false. Despite it being in the for statement at the beginning of the loop, the update is done at the end of the loop, after the last statement in the body.

body

The body of the loop is the code in the curly braces. It’s what is executed over and over again until the test evaluates to false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are some examples of “for loop patterns”?

A

The initialization, test, and update statements allow you to create for loops with lots of different patterns for the loop counter. All the following loop four times, but with different patterns for the loop variable:

for (int i = 0; i < 4; i++) // 0, 1, 2, 3

for (int j = 0; j <= 6; j += 2) // 0, 2, 4, 6

for (int x=4; x>0; x–) // 4, 3, 2, 1

You will often use the value of the loop variable in the body of the code as well to implement a pattern where the repeated lines of code are similar but not exactly the same:

System.out.println(“2 squared = “ + 2 * 2);

System.out.println(“3 squared = “ + 3 * 3);

System.out.println(“4 squared = “ + 4 * 4);

System.out.println(“5 squared = “ + 5 * 5);

System.out.println(“6 squared = “ + 6 * 6);

Here’s a for loop that does the exact same thing:

for (int n = 2; n <= 6; n++) {

System.out.println(n + “ squared = “ + (n * n));

}

Sometimes the first or last time through a loop needs to be a little different, as is the case in this bigger grid:

+—+—+—+

+—+—+—+

| | | |

+—+—+—+

| | | |

+—+—+—+

Here’s one way to code this:

for (int i=1; i<=3; i++) {

System.out.println(“+—+—+—+”);

System.out.println(“|—|—|—|”);

}

System.out.println(“+—+—+—+”);

Or:

System.out.println(“+—+—+—+”);

for (int i=1; i<=3; i++) {

System.out.println(“|—|—|—|”);

System.out.println(“+—+—+—+”);

}

Or, finally you could use an if statement to avoid duplicating the line of code. Which of these variations you use depends on which you think best communicates the purpose of the code.

for (int i=1; i<=4; i++) {

System.out.println(“+—+—+—+”);

if (i < 4) {

System.out.println(“|—|—|—|”);

}

}

| | |

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are “Nested loops”?

A

Just as we could nest if statements inside of if statements, we can nest loops inside of loops. Here’s a simple example:

for (int i = 1; i <= 2; i++) {

System.out.printIn(“Outer i = “ + i);

for (int j = 1; j <= 3; j++) {

System.out.printIn(“ Inner j = “ + j);

}

}

This code produces the following output:

Outer i = 1

Inner j = 1

Inner j = 2

Inner j = 3

Outer i = 2

Inner j = 1

Inner j = 2

Inner j = 3

You can see that the body of the “outer” loop executes 2 times, and for each of those the “inner” loop executes 3 times, a total of 6.

Nested loops like this are often used with two-dimensional tables and matrices with the outer loop handling the rows and the inner loop the columns. This code prints a 5x5 matrix of 0s:

for (int row = 1; row <= 5; row++) {

for (int col = 1; col <= 5; col++) {

System.out.println(“0 “);

}

System.out.println();

}

The output:

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

The inner loop prints a single line of the matrix, and the println that is the last statement of the outer loop body to advances to the next row of the matrix.

This may seem more complicated than just printing “0 0 0 0 0” five times in a single loop, but note that it can deal with each value in the matrix separately. So, by adding an if statement inside the inner loop we can print an “identity matrix” with 1’s on the primary diagonal and zeros elsewhere:

for (int row = 1; row <= 5; row++) {

for (int col = 1; col <= 5; col++) {

if (row == col) {

System.out.print(“1 “);

} else {

System.out.print(“0 “);

}

}

System.out.println();

}

The output:

1 0 0 0 0

0 1 0 0 0

0 0 1 0 0

0 0 0 1 0

0 0 0 0 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a “While loop”?

A

The for loops we’ve used so far are sometimes called “definite” loops, because we know before we start exactly how many times they’re going to repeat. In other situations, we are instead waiting for something to happen _while_ we are looping that will tell us to stop: the user entering a specific command, a timer running out, getting enough questions correct, etc. For these situations, Java provides a while loop. The while loop includes only the test; you have to provide the initialization before the while, and be sure to include the update yourself in the body of the statement.

variable initialization;

while (test) {

body

variable update

}

The following loop prints the sum of all the numbers the user enters as long as it isn’t a zero (assume input has already been declared as a Scanner object):

int sum = 0;

int number = 1;

while (number != 0) {

System.out.println(“Enter a number or 0 to get the sum: “);

number = input.nextInt();

sum += number;

}

System.out.println(“The sum is “ + sum);

The initialization not only sets the value of the running sum to zero, it also has to initialize the value of the variable number to a value that will “force” the loop to execute at least once. The update is the scanner input that changes the value of the number used in the test. Here’s an example while loop that doesn’t let the user out until they enter “yes” or “no”.

String answer = “”;

while (!answer.equals(“yes”) && !answer.equals(“no”)) {

System.out.println(“Enter yes or no: “);

answer = input.getNext();

}

System.out.println(“Thank you!”);

We’ve used boolean logic for this more complicated condition: we continue the loop as long as the user has _not_ entered “yes” AND has _not_ entered “no”. We also had to initialize the loop by setting a value for answer that would force the loop body to execute at least once.

Here’s a variation that lets us use a different message if the user fails to enter the correct phrase the first time. In this case, if they do it right, the loop body doesn’t execute at all. The initialization does, however, duplicate the scanner input statement which MUST be in the body of the loop as well so that the update happens!

System.out.print(“Enter yes or no: “);

String answer = input.getNext();

while (!answer.equals(“yes”) && !answer.equals(“no”)) {

System.out.println(“Enter ONLY yes or no, please: “);

answer = input.getNext();

}

System.out.println(“Thank you!”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly