Python Recursion and Factorial

As the final Computer Science lesson of the 2016/2017 academic year, I reviewed the somewhat concept of recursion in the Python programming language. In this review, I used the mathematical concept of factorial to discuss recursion.

#Program Name: Recursion Sample
#Programmer Name: Eric Evans, M.Ed.
#Program Description: Provide a functional example of a recursion problem in Computer Science using the mathematical concept of factorial.
#
#Define function named factorial which will have an input value of n.
def factorial(n):
    print("Factorial has been called with n = " + str(n))
    if n == 1:
        return 1
    else:
        result = n * factorial(n-1)
        print(n,"! = ",result)
        return result
#Output the function factorial with an input value of 4.
print(factorial(4))

Let’s pull this concept apart line-by-line.

Lines 1 through 5 and line 14 are comment lines and have no real bearing on the program. They simply exist for documentation purposes.

At line 6, we declare a new function named “factorial” that will receive an input of “n”. This is done using the def or define call in Python. The “factorial” function occupies lines 6 through 13.

On line 7, we output the text “Factorial has been called with n = ” concatenated with the value of “n” cast as a string.

On lines 8 and 9, we enter the first part of a conditional statement. At line 8, we use a Boolean equals to see if “n” is equal to 1. If “n” is equal to 1, then line 8 executes and returns the value “1”.

Line 10 begins the process of addressing what to do if “n” does not equal 1.

On line 11, we declare a variable named “result”, which is defined as the value of “n” multiplied by the value of the “factorial” function with an input value that is one less than the current value of “n”.

Line 12 is simply allowing us to see the factorial value of the current “n” value each time through the loop.

Line 13 returns the value of the variable named “result”.

Line 15 calls the “factorial” function and provides it the necessary input to process. In this case, it is a 4.

Now, let’s see what happens when we run this code:

Factorial has been called with n = 4
Factorial has been called with n = 3
Factorial has been called with n = 2
Factorial has been called with n = 1
2 ! =  2
3 ! =  6
4 ! =  24
24

So, let’s see what’s going on with this output.

Lines 1 through 4 of the output are generated by line 7 of the code. That code displays the static words with the dynamic output of the value of “n”. Notice that each time through the loop, it decremented by 1.

Looking at lines 5 through 7 of the output, we see that the calculations actually start with the lowest factorial number of 2 and increment by 1.

Now, if you notice, the way the calculation was coded on line 11, we are performing the following:

  • (Step 1)  4! = 4 X 3!
    • This is the original problem. Solve for 4!, but it is defined needing to know the value of 3!, which is defined in step 2.
  • (Step 2)  3! = 3 X 2!
    • To solve step 1, we need to know the value of 3!. However, it is defined needing to know the value of 2!, which is defined in step 3.
  • (Step 3)  2! = 2 X 1!
    • To solve step 2, we need to know the value of 2!. However, it is defined needing to know the value of 1!, which is defined in step 4.
  • (Step 4)  1! = 1
    • To solve 3, we need to know the value of 1!. It has a given value of 1.
  • (Step 5)  2! = 2 X 1 = 2
    • Now, that we know the value of 1!, we can calculate the value of 2!.
  • (Step 6)  3! = 3 X 2 = 6
    • Now that we know the value of 2!, we can calculate the value of 3!.
  • (Step 7)  4! = 4 X 6 = 24
    • Now that we know the value of 3!, we can calculate the value of 4!, which was the original problem.

As you can see, the final solution is dependent upon the solution of a previous step, which was dependent upon the solution of a previous step, which was dependent upon the solution of a previous step, which – well you get the idea. This is the basic concept of recursion.

Basic Variables in Python

Today, we have been playing with basic variables in Python. The plan is to output something similar to the following:

Hello World
1 + 1 = 2
2 + 2 = 4
4 + 4 = 8

This output is to be generated entirely from calling variables.

#Programmer Name: Eric Evans, M.Ed.
#Program Name: 02 - Hello Variable
#Program Description: Outputs assigned information using only variables.
#
#DECLARATION OF VARIABLES
firstWord = "Hello"
secondWord = "World"
space = ' '
#OUTPUT
print(firstWord + space + secondWord)

Now, as you can see, the first line of the output is somewhat easy to code. We declared the variables firstWord, secondWord, and space and then called them to print concatenated together.

#Programmer Name: Eric Evans, M.Ed.
#Program Name: 02 - Hello Variable
#Program Description: Outputs assigned information using only variables.
#
#DECLARATION OF VARIABLES
firstWord = "Hello"
secondWord = "World"
space = ' '
firstAddend = 1
firstProblemSum = firstAddend + firstAddend
secondAddend = firstProblemSum
secondProblemSum = secondAddend + secondAddend
thirdAddend = secondProblemSum
thirdProblemSum = thirdAddend + thirdAddend
#OUTPUT
print(firstWord + space + secondWord)
print(firstAddend + " + " + firstAddend + " = " + firstProblemSum)
print(secondAddend + " + " + secondAddend + " = " + secondProblemSum)
print(thirdAddend + " + " + thirdAddend + " = " + thirdProblemSum)

Things start to act problematically when we try to produce the last 3 lines of output. When we run the application, we receive an error because we are attempting to mix string and integer variables on a combined output line.

To resolve this issue, we must typecast the integers as strings.

#Programmer Name: Eric Evans, M.Ed.
#Program Name: 02 - Hello Variable
#Program Description: Outputs assigned information using only variables.
#
#DECLARATION OF VARIABLES
firstWord = "Hello"
secondWord = "World"
space = ' '
firstAddend = 1
firstProblemSum = firstAddend + firstAddend
secondAddend = firstProblemSum
secondProblemSum = secondAddend + secondAddend
thirdAddend = secondProblemSum
thirdProblemSum = thirdAddend + thirdAddend
#CASTING OF VARIABLES
firstProblemSum = str(firstProblemSum)
firstAddend = str(firstAddend)
secondProblemSum = str(secondProblemSum)
secondAddend = str(secondAddend)
thirdProblemSum = str(thirdProblemSum)
thirdAddend = str(thirdAddend)
#OUTPUT
print(firstWord + space + secondWord)
print(firstAddend + " + " + firstAddend + " = " + firstProblemSum)
print(secondAddend + " + " + secondAddend + " = " + secondProblemSum)
print(thirdAddend + " + " + thirdAddend + " = " + thirdProblemSum)

As you can see, on lines 15 – 21 we cast each of the integer variables as a string variable. At this point, lines 24 – 26 will execute as expected.

The compilable code can be viewed at https://repl.it/HesM/3

2-Dimensional Arrays in Java

Today, we started to cover 2-dimensional arrays in Java. I decided to start with something very easy:

2-D Array Visual
2-D Array Visual

We have an array with 2 rows and 3 columns. Like all things in Java, we start counting our indices at 0.

As such, the value of [0][0] is Vanilla and [1][0] is Ice Cream. Note that the first number in the reference points to the row and the second number in the reference points to the column.

import java.util.*;
public class TwoDArrays {
    public static void main(String[] args){
        String[][] myBigArray = new String [][] {
            {"Vanilla ", "Chocolate ", "Strawberry "},
            {"Ice Cream", "Cookie", "Candy"}
        };
        System.out.println(myBigArray[0][0] + myBigArray[1][0]);
        System.out.println(myBigArray[0][1] + myBigArray[1][0]);
        System.out.println(myBigArray[0][2] + myBigArray[1][0]);
        
        System.out.println(myBigArray[0][0] + myBigArray[1][1]);
        System.out.println(myBigArray[0][1] + myBigArray[1][1]);
        System.out.println(myBigArray[0][2] + myBigArray[1][1]);
        
        System.out.println(myBigArray[0][0] + myBigArray[1][2]);
        System.out.println(myBigArray[0][1] + myBigArray[1][2]);
        System.out.println(myBigArray[0][2] + myBigArray[1][2]);
    }
}

Line 4 is where we created the 2-dimensional array named “myBigArray”.

Lines 5 and 6 are where we populated the array. Note that line 5 is the first row and line 6 is the second row.

Lines 8 through 18 are where we are outputting text that is “fed” by the 2-D array.

Line 8 concatenates [0][0] with [1][0] which is Vanilla and Ice Cream.

Line 9 concatenates [0][1] with [1][0] which is Chocolate and Ice Cream.

Line 10 concatenates [0][2] with [1][0] which is Strawberry and Ice Cream.

Line 12 concatenates [0][0] with [1][1] which is Vanilla and Cookie.

Line 13 concatenates [0][1] with [1][1] which is Chocolate and Cookie.

Line 14 concatenates [0][2] with [1][1] which is Strawberry and Cookie.

Line 16 concatenates [0][0] with [1][2] which is Vanilla and Candy.

Line 17 concatenates [0][1] with [1][2] which is Chocolate and Candy.

Line 18 concatenates [0][2] with [1][2] which is Strawberry and Candy.

Flipping Stacks

We are now going to look at how to flip a stack. As was discussed previously, a stack is an ideal method for holding items in a queue such as an incoming call center.

Let’s say the following calls come into a call center. They are time-stamped for reference.

Call 5 – (469)382-1285 – 2017-02-13 / 08:02:57
Call 4 – (682)552-3948 – 2017-02-13 / 08:02:45
Call 3 – (214)233-0495 – 2017-02-13 / 08:01:55
Call 2 – (817)927-3849 – 2017-02-13 / 08:01:22
Call 1 – (972)828-1847 – 2017-02-13 / 08:01:13

In this case, the call that has been placed on hold the longest is “Call 1”, which came in at 8:01:13. However, recall that in a stack I can only interact with the item on the TOP of the stack. In this case, that is “Call 5”.

So, we are going to create a system that “flips” this stack over, pulls the new top item off and then returns to stack to its original order so additional calls can go in the place they should.

So, assuming that we have a stack already created for the numbers, we will need to create an empty temporary stack to hold the items. As we move the items over, the temporary stack will look like the following:

Call 1 – (972)828-1847 – 2017-02-13 / 08:01:13
Call 2 – (817)927-3849 – 2017-02-13 / 08:01:22
Call 3 – (214)233-0495 – 2017-02-13 / 08:01:55
Call 4 – (682)552-3948 – 2017-02-13 / 08:02:45
Call 5 – (469)382-1285 – 2017-02-13 / 08:02:57

As you can now see, “Call 1” is at the top of the stack and could be routed to the next available individual. However, if another new call were to come in, the stack would look like the following:

Call 6 – (512)231-1933 – 2017-02-13 / 08:03:19
Call 2 – (817)927-3849 – 2017-02-13 / 08:01:22
Call 3 – (214)233-0495 – 2017-02-13 / 08:01:55
Call 4 – (682)552-3948 – 2017-02-13 / 08:02:45
Call 5 – (469)382-1285 – 2017-02-13 / 08:02:57

To avoid our call queue getting mixed-up, immediately following the retrieval of the top item on the stack, we need to move the items from the temporary stack back to the original stack as follows:

Call 5 – (469)382-1285 – 2017-02-13 / 08:02:57
Call 4 – (682)552-3948 – 2017-02-13 / 08:02:45
Call 3 – (214)233-0495 – 2017-02-13 / 08:01:55
Call 2 – (817)927-3849 – 2017-02-13 / 08:01:22

Now, when “Call 6” comes in, it will go where it is supposed to go (following “Call 5”).

Let’s analyze the code for this problem.

//Program Name: Flipped Stacks
//Programmer Name: Eric Evans, M.Ed.
//Programmer Organization: Ferris High School
//Program Date: Spring 2017
import java.util.*;
public class flippedstacks {
    public static void main(String args[]){
        int count, myStackSize, myTempStackSize;
        Stack myStack = new Stack();
        for (count = 1; count <=10; count++){
            myStack.push(count);
        }
        myStackSize = myStack.size();
        Stack myTempStack = new Stack();
        for (count = 1; count <=myStackSize; count++){
            myTempStack.push(myStack.pop());
        }
        System.out.println("Current Caller is " + myTempStack.pop());
        myTempStackSize = myTempStack.size();
        for (count = 1; count <=myTempStackSize; count++){
            myStack.push(myTempStack.pop());
        }
    }
}

Lines 1 – 4 are the general header information. Lines 5 – 7 are the imports and creation of the class and main object.

Line 8 creates 3 uninitialized integer variables: count, myStackSize, and myTempStackSize.

Line 9 creates a new empty stack named “myStack”.

Lines 10 – 12 push content into the “myStack” stack. It pushes numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, & 10 into the stack.

Line 13 initializes the value of the myStackSize variable as the size of “myStack” using the size function of stacks.

Line 14 is like line 9, but it creates an empty stack named “myTempStack”. This will be the stack that temporarily holds our stack of information so we can get the first record.

Lines 15 – 17 push the content into the “myTempStack” stack by popping each record in the “myStack” stack. The for loop know how many times to do this by using the myStackSize variable that was declared on line 8 and initialized on line 13.

Line 18 displays which caller is the current caller by popping it from the top of the “myTempStack” stack.

Line 19 is like line 13 in that it initializes the value of the myTempStackSize variable as the size of “myTempStack” using the size function of stacks.

Line 19 is also the beginning of the process of reverting the stack back to its original order with the first (oldest) entry removed.

Lines 20 – 22 are similar to lines 15 – 17 but the reverse process. They push content into the “myStack” stack by popping each record in the “myTempStack” stack. The for loop knows how many times to do this by using the myTempStackSize variable that was declared on line 8 and initialized on line 19.

Line 24 & 25 close out lines 7 & 6 respectively.

Arrays with Keyboard Interactivity

Today, we discussed how to create an array with keyboard interactivity. The user will be asked to enter how many numbers they will be entering and then they will be asked to enter numbers separated by a space.

//Program Name: Arrays with Keyboard Input
//Programmer Name: Eric Evans, M.Ed.
//Programmer Organization: Ferris High School
//Program Date: Spring 2017

import java.util.*;
import java.lang.*;
import java.io.*;

public class arrayKeys {
  public static void main(String args[]){
    Scanner count = new Scanner(System.in);
    System.out.print("How Many Numbers Do You Want to Enter?: ");
    int arraySize = count.nextInt();
    int myArray[] = new int[arraySize];
    Scanner nums = new Scanner(System.in);
    System.out.println("Enter Your " + arraySize + " numbers each separated by a space and press enter when done.");
    for(int counter = 0; counter < arraySize; counter++){
      myArray[counter] = nums.nextInt();
    }
  System.out.println(Arrays.toString(myArray));
  }
}

Following the header information (lines 1 through 4) and the imports (lines 6 through 8), we get to the actual application code.

On line 12, we declare a scanner object named “count” which will receive input from the keyboard.

On line 13, we ask the user to enter the number of items they will be entering. Lines 14 assigns the value that is entered as an integer variable named “arraySize”.

Line 15 creates an empty array named “myArray” which is initialized as the size of the “arraySize” variable declared on line 14.

Line 16 declares a second scanner object named “nums” which will receive the integers to the recorded from the keyboard.

On line 17, we ask the user to enter the integers they want recorded separated by a space.

Line 18 opens a for loop. The loop initialization creates an integer variable named “counter” with the value of 0. The loop condition is to run while the variable “counter” is less than the variable “arraySize”, which was declared on line 14. Each pass through the loop increments the value of the variable “counter” by 1.

Each pass through the loop executes line 19, which assigns the next integer in the sequence of numbers from the “nums” scanner to “myArray” in the index (position) declared by the “counter” variable.

Finally, on line 21, we output the contents of “myArray” as a string.

Coding Bat – rotateLeft3

This exercise requires that the program look at an array with 3 integers and shift their positions one index to the left (down) and place first integer (index 0) at the end.

Here is the code that you start with:

public int[] rotateLeft3(int[] nums) {

}

As you can see, we start with an empty integer array named “nums”.

public int[] rotateLeft3(int[] nums) {
  int[] rotatedArray = new int[]{nums[1],nums[2],nums[0]};
  return rotatedArray;
}

 

This solution creates a new integer array named “rotatedArray” and assigns it the values of each index from the original array. (Line 2)

We return the new array on line 3 to solve the problem.

Coding Bat – posNeg

This exercise requires that the program look at two given integers and a boolean. If the Boolean is TRUE AND both integers are negative, then TRUE is returned. If the Boolean is FALSE only 1 integer can be negative for to return TRUE.

Here is the code that you start with:

public boolean posNeg(int a, int b, boolean negative) {

}

As you can see, we start with 2 integer variables named “a” and “b” and a boolean named “negative”.

public boolean posNeg(int a, int b, boolean negative) {
  if (negative){
    if (a < 0 && b < 0){
      return true;
    } else {
      return false;
    } 
  } else if ((a < 0 && b > 0) || (a > 0 && b < 0)) {
    return true;
  } else {
    return false;
  }
}

This solution utilizes a nested if/then structure. Starting on line 2, we say IF the Boolean negative is TRUE, then proceed to line 3. If it is FALSE, we would jump to line 8.

On line 3, we now check to see if both “a” AND “b” are negative (less than 0). If they are, TRUE is returned (line 4). If they are not, FALSE is returned (lines 5-7).

Line 8 is executed if the Boolean on line 3 is FALSE. Line 8 looks to see if “a” is negative and “b” is positive OR “a” is positive and “b” is negative. If either case is TRUE, then TRUE is returned (line 9). If neither statement on line 8 is TRUE, then FALSE is returned (lines 10-12).

Coding Bat presents the following as their solution:

public boolean posNeg(int a, int b, boolean negative) {
  if (negative) {
    return (a < 0 && b < 0);
  }
  else {
    return ((a < 0 && b > 0) || (a > 0 && b < 0));
  }
}

In this solution, line 2 is identical to our line 2. However, their line 3 is shorter version of our lines (3-7). If both “a” AND “b” are not negative, then a FALSE is returned, otherwise a TRUE is returned.

Their lines 5-7 are our lines 8-12 and work the same way.

Coding Bat – Arrays Cluster 1

Today, while I was attending meetings, I assigned my students to complete 4 Coding Bat logic exercises.

CODING BAT – COMMONEND

This exercise requires that the program return TRUE if the first integers or last integers of two given arrays are the same, otherwise, FALSE will be returned.

Here is the code that you start with:

public boolean commonEnd(int[] a, int[] b) {

}

We start with two integer arrays named “a” and “b”.

public boolean commonEnd(int[] a, int[] b) {
  int arrayALength = a.length;
  int arrayBLength = b.length;
  int lastA = a[arrayALength - 1];
  int lastB = b[arrayBLength - 1];
  int firstA = a[0];
  int firstB = b[0];
  if(firstA == firstB || lastA == lastB){
    return true;
  }
  return false;
}

The solution above starts by calculating the length of each array (lines 2 and 3). Remember, whenever you are asked to do anything with the “end” or “last” items, you will almost always need to calculate the length.

On lines 4 & 5, we are establishing variables to hold the last index of each array and lines 6 & 7 are holding the first index of each array.

Finally, lines 8 through 10 are a conditional statement comparing the first indices of each array and the last indices of each array. If either of them are equal, a TRUE is returned. However, if neither is TRUE, then FALSE is returned.

CODING BAT – MAKELAST

This exercise requires that the program calculate the length of a given array and create a new array that is double that length populated with zeros with the exception of the last index. The last index is to populated with the last index of the first array.

Here is the code that you start with:

public int[] makeLast(int[] nums) {

}

We start with a single integer variable named “nums”.

public int[] makeLast(int[] nums) {
 int arrayLength = nums.length;
 int arrayFinalLength = arrayLength * 2;
 int arrayLast = nums[arrayLength - 1];
 int[] num = new int[arrayFinalLength];
 num[arrayLength - 1] = arrayLast;
 return num;
}

As always, since we are asked to do some operation with the “last” or “end”, we must calculate the length of the array. This is done on line 2.

On line 3, we created a variable to hold the length of the new array, which is double the length of the original array.

Line 4 is where we capture the last index of the original array.

On line 5, we create a new integer array named “num” which has a size assigned by the variable that was created on line 3.

On line 6, we replace the last index of the new array with the value of the variable created on line 4.

Finally, on line 7, we return the new array.

CODING BAT – MAKEPI

This exercise requires that the program return the first 3 digits of PI in an array.

Here is the code that you start with:

public int[] makePi() {

}

We start with just the basic class declaration and no variables.

public int[] makePi() {
  int pi[] = {3,1,4};
  return pi;
}

The solution above starts by creating a new integer array named “pi” which is assigned the integers of 3, 1, and 4 on line 2.

On line 3, the array is returned.

Many students struggle to make this problem more challenging than it needs to be. Some try to take the Math.PI constant and populate the array one index at a time. However, this is not necessary and is not outlined as a requirement in the problem.

 

Coding Bat – Cluster 3

Today, while wrapping-up our conversation over arrays, we worked a series of 3 different basic array problems from Coding Bat.

CODING BAT – CIGARPARTY

This exercise requires that the program return true if number of cigars is between 40 and 60 on weekdays and at least 40 on weekends.

Here is the code that you start with:

public boolean cigarParty(int cigars, boolean isWeekend) {

}

We start with a single integer named cigars and a boolean named isWeekend.

public boolean cigarParty(int cigars, boolean isWeekend) {
  if (isWeekend){
    if (cigars >= 40){
      return true;
    }else{
      return false;
    }
  }else{
    if (cigars >=40 && cigars <=60){
      return true;
    }else{
      return false;
    }
  }
}

The solution above starts with a Boolean conditional to check to see if it is a weekend (line 2). If it is not a weekend, then the code jumps to line 8. However, if it is a weekend, the code continues on to line 3.

Line 3 looks to see if the number of cigars is at least 40. If it is, then a TRUE is returned, otherwise a FALSE is returned.

If it is not a weekend, the code jumped to line 8. Starting at line 9, we look to see if the number of cigars is between 40 and 60. If it is, then a TRUE is returned, otherwise a FALSE is returned.

CODING BAT – DATEFASHION

This exercise requires that the program calculate the probability of you and your date getting a table at a restaurant based upon how stylish the clothes you and your date are wearing.

Here is the code that you start with:

public int dateFashion(int you, int date) {

}

We start with two integer variables named “you” and “date”.

public int dateFashion(int you, int date) {
  if (you <= 2 || date <= 2){
    return 0;
  }else if(you >= 8 || date >= 8){
    return 2;
  }else{
    return 1;
  }
}

Our first Boolean conditional statement is located on line 2 where we check to see if either “you” or your “date” are wearing anything that is a 2 or lower. If so, then a “0” is returned.

If the first Boolean is FALSE, then we move to the second Boolean conditional statement on line 4 which is checking to see if either “you” or your “date” are wearing anything that is an 8 or higher. If so, then a “2” is returned.

Finally, if second Boolean is also FALSE, then we automatically return a “1” as the numbers for “you” and your “date” are between 2 and 8 exclusive of those numbers.

CODING BAT – SQUIRRELPLAY

This exercise requires that the program state whether the squirrels will come out to play. The squirrels like to play when the temperature is between 60 and 90 degrees, unless it is summer. In the summer, they will stay out up to 100 degrees.

Here is the code that you start with:

public boolean squirrelPlay(int temp, boolean isSummer) {

}

We start with one integer variable named “temp” and a boolean variable named isSummer.

public boolean squirrelPlay(int temp, boolean isSummer) {
  if (isSummer){
    if (temp >= 60 && temp <= 100){
      return true;
    }else{
      return false;
    }
  }else{
    if (temp >= 60 && temp <= 90){
      return true;
    }else{
      return false;
    }
  }
}

The solution above starts with a Boolean conditional to check to see if it is summer (line 2). If it is not summer, then the code jumps to line 8. However, if it is summer, the code continues on to line 3.

Line 3 looks to see if the temperature is between 60 and 100 degrees. If it is, then a TRUE is returned, otherwise a FALSE is returned.

If it is not summer, the code jumped to line 8. Starting at line 9, we look to see if the temperature is between 60 and 90 degrees. If it is, then a TRUE is returned, otherwise a FALSE is returned.

CODING BAT – ALARMCLOCK

This exercise requires that the program return what time the alarm clock with sound with the given criteria:

  • If it is a vacation weekday, then the alarm will sound at 10:00.
  • If it is a vacation weekend, then the alarm is off.
  • If it a weekday, then the alarm will sound at 7:00.
  • If it is a weekend, then the alarm will sound at 10:00.

Here is the code that you start with:

public String alarmClock(int day, boolean vacation) {

}

As you can see, we have an integer variable named “day” and a Boolean variable named “vacation”.

public String alarmClock(int day, boolean vacation) {
  if (vacation){
    if (day >= 1 && day <= 5){
      return "10:00";
    }else{
      return "off";
    }
  }else{
    if (day >= 1 && day <= 5){
      return "7:00";
    }else{
      return "10:00";
    }
  }
}

Staring at line 2, we have a Boolean conditional which looks to see if it is a vacation. If it is not a vacation day, then the code skips to line 8. If it is a vacation day, then we proceed to line 3 where we look to see if it is a weekday (days 1 through 5). If it is a weekday, the application will return the string “10:00” otherwise, the application returns the string “off”.

Looking at line 9, we are processing for a non-vacation day and look to see if it is a weekday (days 1 through 5) and then return the string “7:00” if it is a weekday. If it is a weekend, then we return the string “10:00”.

Coding Bat – firstLast6

This exercise requires that the program analyze an array of integers and return TRUE if either the first or last integer is a 6. The array is guaranteed to have a minimum length of 1.

Here is the code that you start with:

public boolean firstLast6(int[] nums) {

}

As you can see, we have a single integer array named nums.

public boolean firstLast6(int[] nums) {
 int first = nums[0];
 int last = nums[nums.length-1];
 if (first == 6 || last == 6){
   return true;
 }
 return false;
}

This solution utilizes a conditional if with the Boolean OR to solve the problem.

We start my declaring an integer variable named “first” to retrieve the value of index 0 (line 2).

We then declare an integer variable named “last” to retrieve the value of the last letter (Line 3)

As was the case when working with strings, to retrieve the last index of the array, we must first calculate its length and then subtract 1 from the total length. This will give us the value of the last index of the array.

Lines 4 through 6 are the conditional Boolean OR looking to see if either the first or last number are 6. If the Boolean is TRUE, then TRUE is returned.