Conditional Statements (Boolean Logic)
A boolean variable is a variable that can either be true or false.
Logical Operators: && (and) || (or) ! (not)
Relational Operators:
< (less than) <= (less than or equal) > (greater than) >= (greater than or equal) == (equal to) != (not equal to)
Example 1) boolean s = 5 > 3 || 2 != 2;
//s will be true because 5 > 3 so one of the two conditions is true
Example 2) boolean t = (5 ==3) && (2==2);
// t will be false because 5 is not equal to 3 and both cases must be true to be true
Conditional Statements
The format of an if statement:
if(condition)
{
list of statements...
}
The "list of statements" will only be performed if the condition is TRUE. Also note that the "list of statements'' can be one or more statements.
The braces used are actually only necessary if there is more than one statement to be performed if the condition is true. If there are no braces, only one statement is considered to be tied to the “if”. Let's look at some examples.
if(x < 10)
{
println("Single-digit number");
}
is equivalent to
if(x < 10)
println("Single-digit number");
or even
if(x < 10) println("Single-digit number");
But the two following are NOT equivalent:
if(x < 10)
{
println("Single-digit number");
println(x);
}
if(x < 10)
println("Single-digit number");
println(x);
In the first if, both print statements will only perform if x<10. In the second, only the first print statement is tied to the “if”. The second one will perform no matter what the result of the condition is. Indentation does not determine whether a statement is connected to an “if”, braces do.
In closing, while it is not necessary to put braces for one statement, programmers tend to do so as a good practice. One advantage is not having to remember them later when another statement is added to the “if” block.
Conditions
The condition of an “if” statement must be capable of returning a value of TRUE or FALSE. Additionally, the condition involves making a comparison between one value or expression and another value or expression. Such comparisons require the use of relational operators. Below is a list of relational operators.
The Relational Operators
Operator Meaning Example in if
== is equal to if(x == 3)
!= is not equal to if(x != 3)
< is less than if(x < 3)
> is greater than if(x > 3)
<= is less than or equal to if(x <= 3)
>= is greater than or equal to if(x >= 3)
Equals vs. Is Equal To
One of the first questions asked is what is the difference between = and ==? The difference is that = is used to assign a value to a variable, whereas == is used to determine if a variable contains a value. If a single equal sign is used in the condition, it actually assigns the value to the variable. This is not the intended result and will cause the program to execute incorrectly.
A Fork in the Road
When the condition in an “if” statement is true, the computer performs the statements enclosed in the braces, then moves on to the next portion of the program. But what if the condition is false? The statements inside the braces are ignored and then the computer moves on to the next portion of the program. For example, in the code below, if x is not less than 10, nothing happens.
if(x < 10)
{
println("Single-digit number");
}
While this may be fine in some situations, many times we want the computer to perform one set of actions if a condition is true and another set of actions if the condition is false. This is a job for the if..else statement! Here's the format:
if(condition)
{
list of statements...
}
else
{
other list of statements...
}
The "list of statements" will be performed if the condition is TRUE while the "other list of statements" will be performed if the condition is FALSE. So unlike the if statement, in an if..else statement, something will occur.
Let's look at an example:
if(x < 10)
{
println("Single-digit number");
}
else
{
println("Multi-digit number");
}
The following is equivalent:
if(x >= 10)
{
println("Multi-digit number");
}
else
{
println("Single-digit number");
}
Note that in the second form, the condition is the opposite of the original. By switching the statements in the “if” and “else” portions, the result is the same.
Also, since there is only one statement in each block, the original if..else above could be written more compactly as:
if(x < 10) println("Single-digit number");
else println("Multi-digit number");
In closing, use an if..else when an action is necessary for both true and false values of the particular condition in your program.
Multiple Conditions (Logical Operators AND/OR)
Sometimes it is necessary to evaluate more than one condition in an if statement. For example, to determine whether a person is a teenager, we need to find out if their age is at least 13, but also less than 20. The following if statement would not be sufficient for this task:
if(age >= 13)
{
println("You are a teenager");
}
This won't work if age happens to be, say, 35. It will incorrectly display that a 35-year-old is a teenager since 35 is greater than 13. To correctly address this situation, we can use the logical operator AND, which has the symbol &&:
if(age>=13 && age<20)
{
println("You are a teenager");
}
The && requires that both conditions be met in order to perform the statement in the braces. So if the variable age is 35, it will not enact the display statement since 35 is not less than 20.
Using OR
When only one of two conditions needs to be true to cause some action, the AND operator is not the correct choice. For this task, the OR operator is needed. The symbol for OR is two vertical bars (||). The vertical bar symbol can be found on the backslash key, directly above the enter key. Let's look at an example in which OR will be useful.
Suppose that a game is being played in which scores were being kept for two players in integer variables called score1 and score2. Suppose further that the game is over when one of the player's scores reaches 10. The following if statement could be used to check whether the game is over:
if(score1==10 || score2==10)
{
println("The game is over");
}
The AND operator would not be appropriate here because we don't need both scores to equal 10, just one of them. It is important to note, however, that an OR will still enact the statement in braces if both conditions are true since at least one of them is true. So if both score1 and score2 equal 10, the display statement will still occur.
In closing, when needing to evaluate more than one condition in an if statement, choose AND if both conditions need to be true and choose OR if only one of the conditions needs to be true. Be careful, as the wrong choice will yield unwanted results.
Multiple Choices
Let's begin this discussion with an example programming problem:
Suppose that a program is being written that will display the word version of a two-digit integer between 20 and 59. For example, the integer 32 will be displayed in words as thirty-two. The following code could be used to write the part that will appear before the hyphen (assume that n is an int variable):
if(n>=20 && n<30) println("Twenty");
if(n>=30 && n<40) println("Thirty");
if(n>=40 && n<50) println("Forty");
if(n>=50 && n<60) println("Fifty");
By combining all of the if statements into an (if..else..if) statement. Here is what it would look like
if(n>=20 && n<30) println("Twenty");
else if(n>=30 && n<40) println("Thirty");
else if(n>=40 && n<50) println("Forty");
else if(n>=50 && n<60) println("Fifty");
One more thing
If the value of n was outside the range of 20-59, nothing will happen. For instance, the value 75 does not make any of the conditions true, so nothing is displayed. If we can be sure that n will not be outside the range 20-59, we could write the code as follows:
if(n>=20 && n<30) println("Twenty");
else if(n>=30 && n<40) println("Thirty");
else if(n>=40 && n<50) println("Forty");
else println("Fifty");
Note that in this version, the last condition is omitted. Since it is the only possibility at that point, the program just displays Fifty without needing to check a condition - it has to be in the 50's at that point. The last else then could be considered a default response - if none of the previous conditions are true, just do this.
In closing, use an if..else..if only when you are coding 3 or more conditional statements that are all based on the same variable or expression. For example, the following could not be converted to an if..else..if:
if(x==1) println("One");
if(y==2) println("Two");
if(z==3) println("Three");
More than one of these conditions can be true, since they are based on different variables. So an if.else..if would not make sense.
Iteration
Repetition
An important feature of computer programs is a loop - the ability to repeat a portion of code as many times as needed. Unlike humans, computers have no problem following the same set of instructions over and over. There are two main loops that we will learn to code repetition. The first loop falls under the definition of a definite or counted loop. It is used when we know precisely how many times we need the computer to do something. The name of this structure is the “for” loop. Here is its format:
for(initialization; continuing condition; incrementation)
Here is an example :
for(x=1; x<=10; x++)
{
print((2*x) + " ");
}
This statement says to begin the counter x at 1, continue with the loop as long as x is less than or equal to 10 and count by 1 (x++). For each value of x, the computer is instructed to display 2 times x. So we will see 2 4 6 8 ... 20 on the screen when this code executes.
Let's take a look at each part of the “for” statement:
Ininitialization
The statement "x=1" in the “for loop” initializes the counter x, or gives it a beginning value. Most loops will begin at one (or zero), but not always. It depends on the needs of the program. Inititialize the counter to the value that makes sense. One note: the loop control variable (in this case, x) must be an integer.
Condition The middle part of the “for” statement is what determines the end of the loop. As long as the condition is met, the loop continues. When it is not met, the loop terminates and program flow continues on the next statement after the “for” loop. In the example given earlier, the incrementation of x will eventually cause it to be 11. That value is not less than or equal to 10, so the loop stops.
Incrementation
The statement x++ is shorthand notation for "add 1 to x". There are two other ways to write this statement: x = x + 1 or x+=1. Counting by one is most common in for loops, but there are situations requiring counting by other numbers, or even counting backwards. Here are some examples:
for(x=2; x<=20; x+=2) //count by two's from 2 to 20
for(x=0; x<=100; x+=5) //count by five’s from 0 to 100
for(x=5; x>=1; x--) //count backward by one's from 5 to 1
Counters
What's the count? There are many instances in programs involving loops where we need to count how many times something happens or find the sum of a collection of numbers. "How," you ask? Let's look at a counter variable first.
Let's take an example. Suppose we wish to know how many integer factors a number has. Recall that a factor of a number is an integer that divides evenly into that number. For example, the number 10 has 4 factors: 1, 2, 5, and 10. Let's look at a loop that can accomplish this task. Begin by declaring a counter variable, which we will call factors. A counter variable must be declared as an int since a count must be a whole number. Also, we initialize the counter as 0 since that is where we begin, with a count of nothing.
int factors=0, number=10, loop;
Here is the loop:
for(loop=1; loop<=number; loop++)
{
if(number%loop==0) factors++;
}
Let's examine this code. First note that the value of loop begins at 1 and ends at the number. Here this means we will check all numbers from 1 to 10 to see if they are factors of 10. When value of loop is 1, the condition number%loop==0 is true since the remainder of 12 divided by 1is 0. So the statement factors++ will enact. This statement means add one to factors. So factors is now 1. Now loop takes the value 2, which also divides into 10 evenly. So factors is now 2. The next value of loop is 3 which is NOT a factor of 10, so factors does not change. In the end, only four numbers are found to be factors of 10, so the variable factors is 4.
Summer Time
There are other times where a sum of a group of numbers is needed. For example, suppose we want to find the sum of the numbers from 1 to 100. We need an integer summation variable for the sum because we are adding integers together. This variable must be initialized to 0 just as a counter variable is.
int sum=0, loop;
Here is the loop:
for(loop=1; loop<=100; loop++)
{
sum+=loop; //recall this means add loop to sum
}
Another example: Suppose we wish to find the total cost of a purchase of 5 items in which decimal values are involved. First, declare the variables:
int loop;
double price, total = 0.0;
and now the loop...
for(loop=1; loop<=5; loop++)
{
print("Enter price: ");
price=scannerObject.nextDouble();
total+=price; //add price to total
}
In closing, Counters are always integers. Sums can be ints or doubles depending on what is being summed. Lastly, remember to initialize counts and sums to 0. If this is not done, you will get an error because you are trying to add to a variable that doesn't yet have a value. I guess that means that you can't add something to nothing.
Conditional Repetition
Many times we need repetition of unknown number in programming. A “for” loop is great for known repetition, but what if you don't know how many times you need to do something? That's where the while loop comes in.
Here is the format:
while(condition)
{
list of statements...
}
You will probably note that a while loop looks a lot like an if statement. In fact a while loop is an “if” statement that can repeat. In other words, it keeps asking the question until it gets an answer of false. So as long as the condition is true, it will continue to do the list of statements.
Example:
Suppose we want to enter an unknown number of positive integers and then find the average of those integers. We can't use a “for” loop because we don't know how many numbers there are. We can use a while loop though, and have a negative value represent the signal to stop entering numbers. Here is how we will do it:
int number=0, sum=0, count=0;
while(number>=0)
{
println("Enter a positive integer: ");
number = scannerObject.nextInt();
if(number>=0){count++;sum+=number;}
}
double average = sum / (1.0 *count);
In this example, once a negative number is entered, the condition number>=0 becomes false and the loop is terminated. The computer always checks the condition first before entering the loop. If the condition is true, the loop is entered. If not, it skips to the next line of code that follows the while loop.
While in Place of For
If there were no “for” loop in Java, we could mimic its function with a well-crafted “while” loop. Take note of the following example:
int count=1;
while(count<=10)
{
println(count);
count++;
}
This while loop is equivalent to the following “for” loop:
for(count=1; count<=10; count++)println(count);
Infinite Loops
It is possible to write a while loop that may not stop - meaning its condition never reaches a false state. Take note of the following example:
int count=1;
while(count!=10)
{
println(count);
count+=2;
}
The value of count starts at 1, then becomes 3, 5, 7, etc.... Thus count is always an odd number, making it impossible to equal 10. So the condition count!=10will always be true. An always true condition makes this loop go on forever, causing a crash as the computer can only take so much of this! We call this phenomenon an infinite loop.
Remember: The while loop is useful in situations where repetition is needed, but the number of repetitions is unknown. This usually means that repetition should continue until a given condition is false. Lastly, be careful to ensure the condition can be false or you run the risk of an infinite loop, causing the program to crash
Nested Loops:
A nested loop is a loop placed inside another loop.
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
print("*");
}
println(); // to end the line
}
• Output:
**********
**********
**********
**********
**********
• The outer loop repeats 5 times; the inner one 10 times.
– "sets and reps" exercise analogy
Example: What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
print("*");
}
println();
}
Output:
*
**
***
****
*****
Example:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
print(".");
}
println(line);
}
• Output:
....1
...2
..3
.4
Break and Return:
• break in a loop instructs the program to immediately quit the current iteration and go to the first statement following the loop.
• return in a loop instructs the program to immediately quit the current method and return to the calling method.
• A break or return must be inside an if or an else, otherwise the code after it in the body of the loop will be unreachable.
Break Example:
int d = n - 1;
while (d > 0)
{
if (n % d == 0)
break;
d--;
}
if ( d > 0 ) // if found a divisor
Return Example:
public int search(String[ ] list, String word)
{
for (int k = 0; k < list.length; k++)
{
if (list[k].equals (word)
return k;
}
return -1;
}
** You can also use the statement “return;” to immediately quit a void method.
Caution about Break Statement:
for (int r = 0; r < m.length; r++)
{
for (int c = 0; c < m[0].length; c++)
{
if (m [ r ][ c ] == 'X' )
break;
}
}
**This “break” breaks out of the inner loop but continues with the outer loop.
Recursion
A recursive method is a method that calls itself. Any method that is written recursively could also be written iteratively (an iterative method is a method that does not call itself).
**You will not be required to write a recursive method on the AP Exam but you will have to determine the output of a recursive method. Also, practicing writing recursive methods helps to understand it.
Example: We want to create a method: int factorial(int n) that will return n factorial (n!).
5! = 5*4*3*2*1 = 120
The logic here is that 5! = 5 * 4!
4! = 4* 3!
3! = 3*2!
2! = 2*1!
1! = 1
Base Case:
A base case is when the recursion stops and trace back up the stack that has been called. The base case in this example is 1! because we know it is 1.
public int factorial(int n)
{
if (n == 1) return 1;
else return n*factorial(n-1);
}
Let’s trace factorial (8):
when n = 8, the else clause is performed which calls 8*factorial(7). However, factorial(7) would return 7*factorial(6). This happens until you run factorial(1) which returns 1. So
factorial(2) = 2*1 = 2.
factorial(3) = 3*factorial(2) = 3*2 = 6
factorial(4) = 4*factorial(3) = 4*6 = 24
factorial(5) = 5*factorial(4) = 5*4 = 120
factorial(6) = 6*factorial(5) = 6*120 = 720
factorial(7) = 7*factorial(6) = 7* 720 = 5040
factorial(8) = 8*factorial(7) = 8* 5040 = 40320
Example 2:
println(adder(7)); // 46
public static int adder(int n)
{
if (n<=0)
return 30;
else
return n + adder(n-2);
}
On the first call to adder, n is 7, and on the second call it’s 5 (7 - 2), etc. Notice that in the return portion of the code that each n is added to the next one in the sequence of calls to adder. Finally, when the n parameter coming into adder gets to 0 or less, the returned value is 30. Thus, we have:
7 + 5 + 3 + 1 + 30 = 46
** Base case in example 2 is when adder(-1) is called.
Example 3 (Fibonacci Sequence):
In this problem we will generate the Fibonacci sequence. This important sequence is found in nature and begins as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, …
We notice that beginning with the third term, each term is the sum of the preceding two. Recursively, we can define the sequence as follows:
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n - 1) + fibonacci(n -2)
Using these three lines, we can write a recursive method to find the kth term of this sequence with the call, println( fib(k) ); :
public static int fib(int n)
{
if (n = = 0)
{
return 0;
}
else if(n = = 1)
{
return 1;
}
else
{
return fib(n – 1) + fib(n – 2);
}
}
Practice: Trace the calls for fib(5). How many times was the method fib called?
Answer: 15
PROBLEM SET 2:
1: Write a program to determine a person’s paycheck based on their pay rate and hours worked. Assume that they are paid “time-and-a-half” for any overtime hours (they receive 1.5 times their pay rate for any hours worked over 40). Print the results as shown below.
Test Data (try both):
a)
Input:
Pay Rate = $12.43
Hours = 43
Output:
Regular Pay = $497.20
Overtime Pay = $55.94
Total Pay = $553.14
b)
Input:
Pay Rate = $13.81
Hours = 37
Output:
Regular Pay = $510.97
Overtime Pay = $0.00
Total Pay = $510.97
2: A “Be Prepared” test prep book costs $18.95; “Next Best” costs $21.95. A site called apzone.com offers a special deal: both for $37.95. If you buy three or more copies (in any mix of these two titles), they are $15.95 each. If you buy 12 or more copies, you pay only $14.00 for each.
Write a method:
public float getOrderTotal(int bp, int nb)
that calculates the total for an order of bp copies of “Be Prepared” and nb copies of “Next Best,” taking the above specials into account.
Thoroughly test your program in a main method.
3. In processing, create a program to generate a circle at a random location every 10 seconds or so. Use the ellipse(float x, float y, float xR, float yR) method to create the circle.
4. Write a program that asks the user for an integer, then displays a backwards count from that integer down to 1, finishing with the sum of all of those integers. See below to better understand what is being asked.
Sample Run of the Program (input and output values in bold):
int last = 6
6 + 5 + 4 + 3 + 2 + 1 = 21
5. Create a method called isPrime that returns true if the number is a prime number and false if the number is not a prime.
public boolean isPrime(int n)
Test your method thoroughly
6. Create a method called printNPrimes that will print the first N prime numbers. Use your method isPrime to do this.
Sample:
printNPrimes(5) should print 2 3 5 7 11
7.
public int recur(int a)
{
if (a < 3)
return a + 2;
else return 3*recur(a-2);
}
What is returned by a call to recur(7)?
8) public int recur2(int a)
{
if (a < 0) return 0;
else return 3 + recur2(a-3);
}
What is returned by a call to recur2(7)?
9) public int mystery(int b, int p)
{
if (p==1) return b;
else return b*mystery(b, p-1);
}
a) What is returned by a call to mystery(5,3)?
b) What is an appropriate name for mystery?
10) public static int mystery2(int number)
{
if (number%10==0) return 1;
else return 1 + mystery2(number/10);
}
a) What is returned by a call to mystery2(5438)?
b) What is an appropriate name for mystery2?
11) Using the structure of mystery2, create a method called sumDigits that returns the sum of all digits of the number passed.
More practice for Unit 2: Work in the Programming Module Part 1 from GADOE
(iteration, conditionals, effective use of controls, making assignments, operators and order of operations, and Boolean operations)
Before starting Unit 3: Read over notes on data structures, searching, and sorting on Unit 3