Category Archives: Classwork

Conditionals: Review and re-cap

Flowchart: What is the look of this flowchart when finished?

Screen Shot 2014-10-15 at 12.51.31 PM

  1. What does the program for that flowchart do? Write the full program.
  2. What is a pseudorandom number? What is the code to generate a random number?
  3. In the Gambler’s ruin, when does the user exit the program?
  4. In the Gambler’s ruin, how many while-loops are needed? Explain.
  5. How do you use a while structure to print the integers from 34 through 41 inclusive?
  6. How do you add all the integers from 34 through 41 inclusive? Show code.
  7. Write the code to prompt the user for an integer N. Your program will display a square pattern of asterisks N by N
  8. Write the code to print all even integers from 36 through 12 inclusive.
  9. Write the code for a while loop to prompt the user if he or she wants to continue to input more integers.
  10. The following questions are related to this flowchart:

Screen Shot 2014-10-15 at 12.51.23 PM

a. What is the oval shape used for?

b. What is the code for each instruction in the flowchart?

c. Draw the flowchart to find the two digits in the middle of a 4-digit integer.

Write the code to calculate and display the following output:

 “     1        1”  
 “     2        4” 
 “     3        9”  
 “     4       16”  
 “     5       25”      

Mystery: What does this program do?

for ( int i =1; i < 21 ; i++) 
  {
   System.out.printf( "%10d" ,(int)(1 + Math.random( ) * 6));

   if ( i % 5 == 0 )   # print newline every 5 rolls
    System.out.println();
  }

Simulation: What does this program do? How would you finish it up?

int frequency1 = 0
int frequency2 = 0
int frequency3 = 0
int frequency4 = 0
int frequency5 = 0
int frequency6 = 0

for ( int i =1; i < 6001 ; i++)     // 6000 die rolls
  {
   face = (int)(1 + Math.random( ) * 6);
    
   if (face == 1)                       
    frequency1 += 1                 // frequency counted
   else
   if ( face == 2 )
    ...
   ...
  }



Loop 1: What structure can be used to repeat a block of statements when the termination of the loop is not known? Explain your answer.

Loop 2: What structure can be used to repeat a block of statements when the termination of the loop is known? Explain your answer.

Advanced Topic: Static Methods and the String class

Static Methods:

The Math class:
Math.pow(10, 3)

    In Java, numbers as primitive data types are not objects, so you can never invoke a method on a number.
    Instead, you pass a number as an explicit parameter to a method
    ClassName.methodName(parameters)
  1. What happens to this code fragment when you compile it?

int x = 2;
System.out.println(x.pow(3));

  1. What is the difference between an ADT and a primitive data type? What can you create with an ADT?

The String Class
In Java, strings are objects that belong to the class String.
You do not need to call a constructor to create a string object.

A string is a sequence of characters. Strings are objects of the String class.

The substring method computes substrings of a string.

The call s.substring(start, pastEnd)

returns a string that is made up of the characters in the string s, starting at position start, and containing all characters up to, but not including, the position pastEnd.

Here is an example:
String greeting = “Hello, World!”;
String sub = greeting.substring(0, 5); // sub is “Hello”

H e l l o ,   W o r  l  d  !
0 1 2 3 4 5 6 7 8 9 10 11 12


The position number of the last character (12 for the string “Hello, World!”) is always 1 less than the length of the string.

Let us figure out how to extract the substring “World”.
Count characters starting at 0, not 1. You find that W, the eighth character, has position number 7. The first character that you don’t want, !, is the character at position 12 .

               <-----5---->
H e l l o ,   |W o r  l  d | !
0 1 2 3 4 5 6 |7 8 9 10 11 | 12


String sub2 = greeting.substring(7, 12);

You can easily compute the length of the substring: It is pastEnd – start. For example, the string “World” has length 12 – 7 = 5.

If you omit the second parameter of the substring method, then all characters from the starting position to the end of the string are copied.

For example,
String tail = greeting.substring(7); // tail is “World!”

  1. Why can you have multiple substring methods doing something different?

If you supply an illegal string position (a negative number, or a value that is larger than the length of the string), then your program terminates with an error message.

  1. Will it be an error during compilation or at run time?

Strings and the char Type
Strings are sequences of Unicode characters.
Character literals look like string literals, but we use single quotes: ‘M’ is a character, “M” is a string containing a single character.

Characters have integer values.
Screen Shot 2015-02-11 at 9.53.31 AM

You can use escape sequences inside character literals. For example, ‘\n’ is the newline character, and ‘\u00E9’ is the character é.

“When Java was first designed, each Unicode character was encoded as a two-byte quantity. The char type was intended to hold the code of a Unicode character. However, as of 2003, Unicode had grown so large that some characters needed to be encoded as pairs of char values. Thus, you can no longer think of a char value as a character. Technically speaking, a char value is a code unit in the UTF-16 encoding of Unicode. That encoding represents the most common characters as a single char value, and less common or supplementary characters as a pair of char values.” Clay Horstmann

Screen Shot 2015-02-11 at 12.59.39 PM

The charAt method of the String class returns a code unit from a string. As with the substring method, the positions in the string are counted starting at 0.
For example, the statement

String greeting = “Hello”;
char ch = greeting.charAt(0);

sets ch to the value ‘H’.

  1. How do you find out the number of characters a string has?
  2. How can you create an array of char type containing all the characters of a string?

Visit edmodo.com to answer these questions.

Conditionals: Car Loan

Classwork/Homework:

    1. Write a java program CarLoan_YI.java to print a table giving the total amount paid and the remaining principal after each monthly payment.
      • Prompt the user for the amount, interest and number of years.
      • The prompt should include relevant messages so the user understands the input format.
      • One of your runs should be with the data given below.

      NOTE: your program properly handles an interest rate of 0% and avoids dividing by 0.

      Click on the image to understand the formula

      Example output:
      Amount borrowed = 1000.00
      Number of years = 2

      Interest rate = 3.00
      Monthly payments = 42.98
      Total interest = 31.55
      If the total interest is pre-paid here is a chart:

      Month     Amt Paid      Remaining
       1           42.98         957.02
       2           85.96         914.04
       3          128.94         871.06
       4          171.92         828.08
       5          214.91         785.09
       6          257.89         742.11
       7          300.87         699.13
       8          343.85         656.15
       9          386.83         613.17
      10          429.81         570.19
      11          472.79         527.21
      12          515.77         484.23
      13          558.76         441.24
      14          601.74         398.26
      15          644.72         355.28
      16          687.70         312.30
      17          730.68         269.32
      18          773.66         226.34
      19          816.64         183.36
      20          859.62         140.38
      21          902.61          97.39
      22          945.59          54.41
      23          988.57          11.43
      
      

      If the total interest if included in the monthly payments, here is a chart:

      Courtesy from Diane Li

      /**
      Input/Output:
      Enter the loan amount in dollars:
      1000
      Enter the loan term in years:
      2
      Enter the annual interest rate as a percentage:
      3
      Month   Amount Paid   Remaining
      
      1     42.98          988.56
      2     85.96     945.58
      3    128.94     902.60
      4    171.92     859.62
      5    214.90     816.64
      6    257.88     773.66
      7    300.86     730.68
      8    343.84     687.69
      9    386.83     644.71
      10   429.81     601.73
      11   472.79     558.75
      12   515.77     515.77
      13   558.75     472.79
      14   601.73     429.81
      15   644.71     386.83
      16   687.69     343.84
      17   730.68     300.86
      18   773.66     257.88
      19   816.64     214.90
      20   859.62     171.92
      21   902.60     128.94
      22   945.58      85.96
      23   988.56      42.98
      24      1031.54           0.00
      
      **/
      

      Even though this chart doesn’t reflect the finance charge, it is an effective way to show the amount paid and the remaining values. In some cases, the finance charge is paid up front.
      screen-shot-2016-10-04-at-2-34-18-pm

      Optional

      screen-shot-2016-10-04-at-2-44-34-pm

       

      Car Loans | How Does Car Loan Interest Work? | IFS How does car loan interest affect you? Most car loans use simple interest. Learn more about car loan interest – it could save you money.

       

      If you really want the challenge of using the amortization model here is a chart that can show the effect of how the interest charges decrease as the amount borrowed also decreases.

      screen-shot-2016-10-04-at-2-44-34-pm

Conditionals: CompoundIntTable_YI.java – Needs fixing

Screen Shot 2014-09-23 at 10.00.31 AM

NO MORE MAGIC NUMBERS

Things to keep in mind when submitting your work:
1. Copy and paste your program in the post.
2. Attach your file(s).
3. Make sure your program has a header and the input/output.
4. If your program doesn’t run, an explanation should be the first line in the post.

Screen Shot 2014-09-28 at 12.38.49 PM

Classwork:
YI_CompoundIntTable.java: Use a while loop to show how the investment increases as the accumulated total becomes at least $1,100 at an interest rate of 1.2% when $1,000 is deposited in a savings bank account.

The table should have the following columns:


year      accum interest/year          total accumulated up to this year  
 1        12.0                         1012.0
 2        24.14                        1024.14
 3        36.43                        1036.43
...

Number of years for the investment of $1000 to reach at least a value of $1,100 with an interest rate of 1.2% is  8

Homework:
CompIntCompareTable_YI.java: Create another table that compares how you use the formula P(1+r)^t, where t is the number of years and how your program calculates the equivalent values.
End up your assignment with a conclusion about the similarities and the differences between the two approaches.

Conditionals: Asterisks

Screen Shot 2014-10-02 at 10.05.29 AM

Asterisks Pattern
If you are finished with yesterday’s programming assignment, work on the following assignment.
Write a program, Asterisks_YI.java that prints the following pattern separately, one below the other each pattern separated front he next by one blank line. Use nested for loops ONLY to generate the patterns. All asterisks (*) should be printed by a single statement
which causes the asterisks to print side by side separated by a space.
Hint: The last two patterns require that each line begin with an appropriate number of blanks.

Extra Credit: Combine your code from the four separate problems into a single program that prints all four patterns side by side by making clever use of nested for loops. For all parts of this program – minimize the number of statements that print these characters.
asteriskspattern

/**
 * 4 patterns using asterisks
 * Basic program to start with
 * It draws a square of asterisks
 *
 * @mrs.e
 * @11/19/19
 */
public class Asterisks
{
    public static void main(String args[])
    {
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                System.out.print("* ");
            }
            
            System.out.println();                   
        }
    }
}

* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 


Conditionals: Random Walker(s) Project

Screen Shot 2014-10-02 at 10.05.29 AM

Programming Project 1:
a. A drunkard’s walk. A drunkard begins walking aimlessly, starting at a lamp post. At each time step, the drunkard forgets where he or she is, and takes one step at random, either north, east, south, or west, with probability 25%. How far will the drunkard be from the lamp post after N steps?
More details on edmodo.com
Project 1 # 4: A drunkard’s walk

b. Write a program RandomWalkers.java that takes two integer command-line arguments N and T. In each of T independent experiments, simulate a random walk of N steps and compute the squared distance. Output the mean squared distance (the average of the T squared distances).

As N increases, we expect the random walker to end up farther and farther away from the origin. But how much farther? Use RandomWalkers to formulate a hypothesis as to how the mean squared distance grows as a function of N. Use T = 100,000 trials to get a sufficiently accurate estimate.

Conditionals: Gambler: Modified Version

 

Modify Gambler.java to take an extra command line parameter that specifies the number of bets the gambler is willing to make so that there are three possible ways for the game to end:
* the gambler wins, loses, or runs “out of time” meaning the gambler gives up.
* Add to the output to give the expected amount of money the gambler will have when the game ends.

Think of the different outcomes and how would report on them. That means what your output would look like and how you would display it. Look back to the format of the previous gambler’s ruin activity.

A random(get it?) example:

stake: $5 goal: $10 trials: 10 games and run out of time is 7 bets

1 game – lost all your money
2 game – won
3 game – end by the 7th bet and you had $6
4 game – lost all your money
5 game – end by the 7th bet and you had $4
6 game – lost all your money
7 game – won
8 game – end by the 7th bet and you had $2
9 game – won
10 game – lost all your money

6 + 4 + 2 = 12 total accumulated from “run out of time”
the expected amount of money from 10 games is 12/3 = $4

Lesson slides on page 28

public class Gambler
{
    public static void main(String[] args)
   {
     int stake = Integer.parseInt(args[0]);
     int goal = Integer.parseInt(args[1]);
     int trials = Integer.parseInt(args[2]);

    int wins = 0;
    for (int i = 0; i < trials; i++)
     {
       int t = stake;
       while (t > 0 && t < goal)
        {
            if (Math.random() < 0.5) t++;
            else t--;
        }
        if (t == goal) wins++;
     }
   StdOut.println(wins + " wins of " + trials);  
   }
}

Conditionals: Gambler: Chart

WARNING: your program should run only once and produce this chart:
a. Modify the original gambler to show how the increase of “trials” affects the probability of winning.

A good easy format:
stake = 5 goal = 25

Trials Wins Probability
100 15%
1000 19%
10000 22%
100000 20%
1000000 20%

WARNING: your program should run only once and produce this chart:
b. Modify the original gambler to show how the increase of the “stake” affects the probability of winning.

A good easy format:
goal = 25 trials = 1000

Stake Wins Probability
5 17%
10 39%
15
20

WARNING: your program should run only once and produce this chart:
c. Modify the original gambler to show how the increase of the “goal” affects the probability of winning.

A good easy format:
stake = 5 trials = 1000

Goal Wins Probability
5 98%
10 50%
15
20
25

Conditionals: Project Euler: Sum Square Difference

Sum square difference

Problem 6

The sum of the squares of the first ten natural numbers is,

12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

/** the correct output  is 25164150 **/

Conditionals: Gambler: Questions

From page 28 on this pdf:
1. What is the “if (t == goal) wins++; ” keeping track of?
2. What does the outer loop control?
3. What happens at each trial?
4. What is the identifier “win” for?
5. What is the “stake” for?
6. What is the “goal” for?
7. How many trials would produce a good result?
8. How do you read the output in plain English?
% java Gambler 5 25 1000
203 wins of 1000

  1. If you were running this program to find the probability of winning in this game, what would need to be done to come up with the best approximation to the actual value?

a. Implement another loop that will increase the goal by doubling it at every iteration and report the conclusion. Keep all other variables fixed. The stake should be $5.

b. Implement another loop that will increase the trials by factors of 10 it at every iteration and report the conclusion. Keep all other variables fixed. The stake should be $5.

Challenge (Optional):

Add what is needed to be able to systematically increase both the goals and the trials. Report your result in full a sentence.

public class Gambler
{
    public static void main(String[] args)
   {
     int stake = Integer.parseInt(args[0]);
     int goal = Integer.parseInt(args[1]);
     int trials = Integer.parseInt(args[2]);

    int wins = 0;
    for (int i = 0; i < trials; i++)
     {
       int t = stake;
       while (t > 0 && t < goal)
        {
            if (Math.random() < 0.5) t++;
            else t--;
        }
        if (t == goal) wins++;
     }
   StdOut.println(wins + " wins of " + trials);  
   }
}