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.

Advanced Topic: Static Identifier

The Static Specifier

foxtrot.100.in.binary

NOTE: use the implementation already written from the previous assignment but pay attention to the changes.
(The YI_MyStaticInteger class) Design a class named MyInteger. The class contains:
■ A static int data field named intCount that stores the number of object of this class created in the driver.
■ An int data field named value that stores the int value represented by this object.
■ A constructor that creates a MyStaticInteger object for the specified int value and updates the intCount data field.
■ A get method that returns the int value.
■ A get method that returns the int intCount.
■ The methods isEven(), isOdd(), and isPrime() that return true if the value in this object is even, odd, or prime, respectively.
■ The static methods isSEven(), isSOdd(), and isSPrime() that return true if the value in this object is even, odd, or prime, respectively. Comment out the code that causes any problem to be able to continue successfully with the implementation.
■ Compare the last two methods behaviors and explain the differences.
■ Report any problems and messages as comments and explain what the problem is. If you can’t figure it out, watch yesterday’s video again.
■ The static method getintCount() should be part of the class and used in the driver to display the number of object of MyStaticInteger class.

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: Project Euler

https://projecteuler.net/

About Project Euler

Leonhard Euler (1707-1783)

What is Project Euler?

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.

 

Who are the problems aimed at?

The intended audience include students for whom the basic curriculum is not feeding their hunger to learn, adults whose background was not primarily mathematics but had an interest in things mathematical, and professionals who want to keep their problem solving and mathematics on the cutting edge.

 

Can anyone solve the problems?

The problems range in difficulty and for many the experience is inductive chain learning. That is, by solving one problem it will expose you to a new concept that allows you to undertake a previously inaccessible problem. So the determined participant will slowly but surely work his/her way through every problem.

 

What next?

In order to track your progress it is necessary to setup an account and have Cookies enabled. If you already have an account then Login, otherwise please Register – it’s completely free!

However, as the problems are challenging then you may wish to view the Problems before registering.

 

“Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics.”

 

Conditionals: Monty Hall

monty-hall

Assignment:
Game simulation.
In the game show Let’s Make a Deal, a contestant is presented with three doors. Behind one door is a valuable prize, behind the other two are gag gifts. After the contestant chooses a door, the host opens up one of the other two doors (never revealing the prize, of course).

The contestant is then given the opportunity to switch to the other unopened door. Should the contestant do so? Intuitively, it might seem that the contestant’s initial choice door and the other unopened door are equally likely to contain the prize, so there would be no incentive to switch. Write a program MonteHall_YI.java to test this intuition by simulation.

Your program should take an integer command-line argument n, play the game n times using each of the two strategies (switch or don’t switch) and print the chance of success for each strategy.

End the program with a message stating the conclusion: Is a bigger chance of winning if you switch to a different door?

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.