Category Archives: Homework

Built-In: Types of Data Concepts

Screen Shot 2014-09-09 at 10.24.34 PM

Classwork:
Let’s add more to our notes. Please take notes and share your document with me. Use mrseliaphs@gmail.com to share your notes.

  • Basic definitions
  • Characters and Strings
  • Integers
  • Real numbers
  • Booleans
  • Comparisons
  • Type conversion

Exercises 1 through 4 from Built-in Types of Data

  1. Suppose that a and b are int values. What does the following sequence of statements do? Explain with a full and simple sentence.
    int t = a;
    b = t;
    a = b;
  2. Suppose that a and b are int values. Simplify the following expression: (!(a < b) && !(a > b))
  3. The exclusive or operator ^ for boolean operands is defined to be true if they are different, false if they are the same. Give a truth table for this function.
  4. Why does 10/3 give 3 and not 3.33333333?

data type is a set of values and a set of operations defined on them. For example, we are familiar with numbers and with operations defined on them such as addition and multiplication. There are eight different built-in types of data in Java, mostly different kinds of numbers. We use the system type for strings of characters so frequently that we also consider it here.

built-in data types

Terminology. We use the following code fragment to introduce some terminology:

int a, b, c;
a = 1234;
b = 99;
c = a + b;

The first line is a declaration statement that declares the names of three variables using the identifiers ab, and c and their type to be int. The next three lines are assignment statements that change the values of the variables, using the literals 1234 and 99, and the expression a + b, with the end result that c has the value 1333.

Characters and strings. A char is an alphanumeric character or symbol, like the ones that you type. We usually do not perform any operations on characters other than assigning values to variables. A String is a sequence of characters. The most common operation that we perform on strings is known as concatenation: given two strings, chain them together to make a new string. For example, consider the following Java program fragment:

String a, b, c;
a = "Hello,";
b = " Bob";
c = a + b;

The first statement declares three variables to be of type String. The next three statements assign values to them, with the end result that c has the value "Hello, Bob". Using string concatenation, Ruler.java prints the relative lengths of the subdivisions on a ruler.

Integers. An int is an integer (whole number) between −231 and 231 − 1   (−2,147,483,648 to 2,147,483,647). We use ints frequently not just because they occur frequently in the real world, but also they naturally arise when expressing algorithms. Standard arithmetic operators for addition, multiplication, and division, for integers are built into Java, as illustrated in IntOps.java and the following table:

int expressions

Floating-point numbers. The double type is for representing floating-point numbers, e.g., for use in scientific applications. The internal representation is like scientific notation, so that we can compute with real numbers in a huge range. We can specify a floating point number using either a string of digits with a decimal point, e.g., 3.14159 for a six-digit approximation to the mathematical constant pi, or with a notation like scientific notation, e.g., 6.022E23 for Avogadro’s constant 6.022 × 1023. Standard arithmetic operators for addition, multiplication, and division, for doubles are built in to Java, as illustrated in DoubleOps.java and the following table:

double expressions

Quadratic.java shows the use of doubles in computing the two roots of a quadratic equation using the quadratic formula.

Booleans. The boolean type has just two values: true or false. The apparent simplicity is deceiving—booleans lie at the foundation of computer science. The most important operators defined for the boolean are for andor, and not.

  • and:  a && b is true if both a and b are true, and false otherwise.
  • or:  a || b is true if either a or b is true (or both are true), and false otherwise
  • not:  !a is true if a is false, and false otherwise.

Although these definitions are intuitive and easy to understand, it is worthwhile to fully specify each possibility for each operation in a truth table.

boolean operations

Comparisons. The comparison operators are mixed-type operations that take operands of one type (e.g., int or double) and produce a result of type boolean. These operations play a critical role in the process of developing more sophisticated programs.

comparison operations

LeapYear.java tests whether an integer corresponds to a leap year in the Gregorian calendar.

Library methods and APIs.

 Many programming tasks involve using Java library methods in addition to the built-in operators. An application programming interface is a table summarizing the methods in a library.

  • Printing strings to the terminal window.

    printing to standard output

  • Converting strings to primitive types.

    parsing command-line arguments

  • Mathematical functions.

    math library

You can call a method by typing its name followed by arguments, enclosed in parentheses and separated by commas. Here are some examples:

library calls

We often find ourselves converting data from one type to another using one of the following approaches.

Type conversion.

 We often find ourselves converting data from one type to another using one of the following approaches.

    • Explicit type conversion. Call methods such as Math.round()Integer.parseInt(), and Double.parseDouble().
    • Automatic type conversion. For primitive numeric types, the system automatically performs type conversion when we use a value whose type has a larger range of values than expected.

  • Explicit casts. Java also has some built-in type conversion methods for primitive types that you can use when you are aware that you might lose information, but you have to make your intention using something called a castRandomInt.java reads an integer command-line argument n and prints a “random” integer between 0 and n−1.
  • Automatic conversions for strings. The built-in type String obeys special rules. One of these special rules is that you can easily convert any type of data to a String by using the + operator.

type conversion

Exercises

  1. Suppose that a and b are int values. What does the following sequence of statements do?
    int t = a;
    b = t;
    a = b;
    

    Solution: sets ab, and t equal to the original value of a.

  2. Suppose that a and b are int values. Simplify the following expression: (!(a < b) && !(a > b))
    Solution(a == b)
  3. The exclusive or operator ^ for boolean operands is defined to be true if they are different, false if they are the same. Give a truth table for this function.
  4. Why does 10/3 give 3 and not 3.33333333?
    Solution: Since both 10 and 3 are integer literals, Java sees no need for type conversion and uses integer division. You should write 10.0/3.0 if you mean the numbers to be double literals. If you write 10/3.0 or 10.0/3, Java does implicit conversion to get the same result.
  5. What do each of the following print?
    1. System.out.println(2 + "bc"); prints: 2bc
    2. System.out.println(2 + 3 + "bc"); prints: 5bc
    3. System.out.println((2+3) + "bc"); prints: 5bc
    4. System.out.println("bc" + (2+3)); prints: bc5
    5. System.out.println("bc" + 2 + 3); prints: bc23

    Explain each outcome.

  6. Explain how to use Quadratic.java to find the square root of a number.
    Solution: to find the square root of c, find the roots of x^2 + 0x – c.
  7. A physics student gets unexpected results when using the code
    double force = G * mass1 * mass2 / r * r; 
    

    to compute values according to the formula F = Gm1m2 / r2. Explain the problem and correct the code.
    Solution: It divides by r, then multiplies by r (instead of dividing by r *r). Use parentheses:

    double force = G * mass1 * mass2 / (r * r);
    
  8. Write a program Distance.java that takes two integer command-line arguments x and y and prints the Euclidean distance from the point (xy) to the origin (0, 0).
  9. Write a program SumOfTwoDice.java that prints the sum of two random integers between 1 and 6 (such as you might get when rolling dice).
  10. Write a program SumOfSines.java that takes a double command-line argument t (in degrees) and prints the value of sin(2t) + sin(3t).
  11. Write a program SpringSeason.java that takes two int values m and d from the command line and prints true if day d of month m is between March 20 (m = 3, d =20) and June 20 (m = 6, d = 20), false otherwise.

Creative Exercises

  1. Wind chill. Given the temperature t (in Fahrenheit) and the wind speed v (in miles per hour), the National Weather Service defines the wind chill to be:

    w = 35.74 + 0.6215 t + (0.4275 t – 35.75) v0.16

    Write a program WindChill.java that takes two double command-line arguments t and v and prints the wind chill. Use Math.pow(a, b) to compute ab. Note: the formula is not valid if t is larger than 50 in absolute value or if v is larger than 120 or less than 3 (you may assume that the values you get are in that range).

  2. Polar coordinates. Write a program CartesianToPolar.java that converts from Cartesian to polar coordinates. Your program should take two real numbers x and y on the command line and print the polar coordinates r and θ. Use the Java method Math.atan2(y, x), which computes the arctangent value of y/x that is in the range from -π to π.
  3. Day of the week. Write a program DayOfWeek.java that takes a date as input and prints the day of the week that date falls on. Your program should take three command-line arguments: m (month), d (day), and y (year). For m use 1 for January, 2 for February, and so forth. For output print 0 for Sunday, 1 for Monday, 2 for Tuesday, and so forth. Use the following formulas, for the Gregorian calendar (where / denotes integer division):

    y0 = y − (14 − m) / 12
    x = y0 + y0/4 − y0/100 + y0/400
    m0 = m + 12 × ((14 − m) / 12) − 2
    d0 = (d + x + 31m0 / 12) mod 7

    For example, on which day of the week was August 2, 1953?

    y0 = 1953 - 0 = 1953
    x = 1953 + 1953/4 - 1953/100 + 1953/400 = 2426
    m0 = 8 + 12*0 - 2 = 6
    d0 = (2 + 2426 + (31*6) / 12) mod 7 = 2443 mod 7 = 0  (Sunday)
    

  4. Uniform random numbers. Write a program Stats5.java that prints five uniform random values between 0 and 1, their average value, and their minimum and maximum value. Use Math.random()Math.min(), and Math.max().
  5. Three-sort. Write a program ThreeSort.java that takes three int values from the command line and prints them in ascending order. Use Math.min() and Math.max().
  6. Dragon curves. Dragon curvesWrite a program Dragon.java to print the instructions for drawing the dragon curves of order 0 through 5. The instructions are strings of the characters FL, and R, where F means “draw line while moving 1 unit forward”, L means “turn left”, and R means turn right. A dragon curve of order n is formed when you fold a strip of paper in half n times, then unfold to right angles. The key to solving this problem is to note that a curve of order n is a curve of order n−1 followed by an L followed by a curve of order n−1 traversed in reverse order, and then to figure out a similar description of the reverse curve.

Web Exercises

  1. Write a program Swap.java that takes two integer command-line arguments a and b and swaps their values using the swapping idiom described on p. 17. After each assignment statement, use System.out.println() to print a trace of the variables.
  2. What does the following statement do where grade is a variable of type int?
    boolean isA = (90 <= grade <= 100);
    

    Solution: Syntax error since <= is a binary operator. You can rewrite the expression as (90 <= grade && grade <= 100).

  3. RGB to YIQ color converter. Write a program RGBtoYIQ.javathat takes an RGB color (three integers between 0 and 255) and transforms it to a YIQ color (three different real numbers YI, and Q, with 0 ≤ Y ≤ 1, –0.5957 ≤ I ≤ 0.5957, and –0.5226 ≤ Q ≤ 0.5226). Write a program YIQtoRGB.java that applies the inverse transformation.
  4. CMYK to RGB color matching. Write a program CMYKtoRGB that reads in four command line inputs C, M, Y, and K between 0 and 1, and prints the corresponding RGB parameters. Devise the appropriate formula by “inverting” the RGB to CMYK conversion formula.
  5. What does the following code fragment print?
    double x = (double) (3/5);
    System.out.println(x);
    

    Solution: It prints 0.0 since the integer division is done before the cast.

  6. Why doesn’t the following program print 4294967296 = 2^32?
    int x = 65536;
    long y = x * x;
    System.out.println(y);
    

    Solution: The product of the two int values is computed as an int, and then automatically converted to a long. But 65536 * 65536 = 2^32 overflows a 32 bit int before it gets converted.

  7. What is the value of (Math.sqrt(2) * Math.sqrt(2) == 2)?
  8. Write a program DivideByZero.java to see what happens when you divide an int or double by zero.
    Solution:

     

    • (17 / 0) and (17 % 0) result in a division by zero exception;
    • (17.0 / 0.0) results in a value Infinity;
    • (17.0 % 0.0) results in a value NaN that stands for “not a number.”
  9. Guess the biggest number. Consider the following game. Alice writes down two integers between 0 and 100 on two cards. Bob gets to select one of the two cards and see its value. After looking at the value, Bob commits to one of the two cards. If he chooses a card with the largest value, he wins; otherwise he loses. Devise a strategy (and corresponding computer program) for Bob so that he guarantees to win strictly more than half the time.
  10. Fibonacci word. Write a program FibonacciWord.java that prints the Fibonacci word of order 0 through 10. f(0) = “a”, f(1) = “b”, f(2) = “ba”, f(3) = “bab”, f(4) = “babba”, and in general f(n) = f(n-1) followed by f(n-2). Use string concatenation.
  11. Standard deviation. Modify Exercise 1.2.30 so that it prints the sample standard deviation in addition to the average.
  12. Write a program that reads in three parameters and prints true if all three are equal, and false otherwise.
  13. What happens if you compile LeapYear.java and execute it with
    1. java LeapYear
    2. java LeapYear 1975.5
    3. java LeapYear -1975
    4. java LeapYear 1975 1976 1977
  14. What does the compiler do if you try to write the following expression:
    int a = 27 * "three";
    
  15. What does the compiler do if you try to write the following expression:
    double x;
    System.out.println(x);
    

    Solution: The compiler complains that the variable x might not have been initialized. Variables within main are not automatically initialized.

  16. What does the following code fragment print.
    int threeInt = 3;
    int fourInt  = 4;
    double threeDouble = 3.0;
    double fourDouble  = 4.0;
    System.out.println(threeInt / fourInt);
    System.out.println(threeInt / fourDouble);
    System.out.println(threeDouble / fourInt);
    System.out.println(threeDouble / fourDouble);
    
  17. Write a program that takes four real-valued command line parameters x1, y1, x2, and y2 and prints the Euclidean distance between the points (x1, y1) and (x2, y2). Use Math.sqrt().
  18. Write a program Ordered.java that reads in three integer command line arguments, xy, and z. Create a boolean variable b that is true if the three values are either in ascending or in descending order, and false otherwise. Print the variable b.
  19. Write a program Divisibility.java that reads in two command line inputs and prints true if both are divisible by 7, and false otherwise.
  20. Area of a triangle. Write a program TriangleArea.java that takes three command line inputs a, b, and c, representing the side lengths of a triangle, and prints the area of the triangle using Heron’s formula: area = sqrt(s(s-a)(s-b)(s-c)), where s = (a + b + c) / 2.
  21. Equatorial to horizontal coordinates. The equatorial coordinate system is widely used by astronomers to indicate the position of a star on the celestial sphere. The position is specified by its declination δ, its hour angle H, and its latitude φ. The horizontal coordinate system (a.k.a. Alt/Az coordinate system) is useful for determining the setting/rising time of celestial objects. The position is specified by its altitude (vertical angle from the horizon) and and its azimuth (horizontal angle). Given a star’s position using equatorial coordinates, find its position in horizontal coordinates using the formulas below.
    Altitude = asin (sin φ sin δ  + cos φ cos δ cos H)
    Azimuth  = acos ((cos φ sin δ  - sin φ cos δ cos H) / cos (Altitude) )
    
  22. Body mass index. The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a program BMI.java that takes two command-line arguments, weight and height, and prints the BMI.
  23. Temperature conversion. What is wrong with the following code fragment to convert from Fahrenheit (F) to Celsius (C)?
    double C = (F - 32) * (5 / 9);
    
  24. Exponentiation. What is wrong with the following code fragment to compute a2, where a is of type double?
    double b = a^2;
    

    Solution: In Java, ^ does not mean exponentiation (it’s the exclusive or function from logic). Use a*a instead. To compute ax, use Math.pow(a, x). Note that Math.pow() returns a double so that you would need an explicit cast if a and b in the above example were integers.

  25. What of the following statements is legal?
    boolean b = 1;
    boolean b = true;
    boolean b = "true";
    boolean b = True;
    

    Solution: Only the second one.

  26. Barring overflow, give a code fragment to compute the maximum of two integers a and b without using Math.max() or if.
    int max = (a + b + Math.abs(a - b)) / 2;
    
  27. Discriminant of cubic polynomial. Given the coefficients b, c, and d of the cubic polynomial x^3 + bx^2 + cx + d, write an expression to compute the discriminant b^2c^2 – 4c^3 – 4b^3d – 27d^2 + 18bcd.
  28. Barycenter. In a two-body system, the barycenter is the center of gravity about which the two celestial bodies orbit each other. Given the masses m1 and m2 of two bodies, and the shortest distance a between the two bodies, write a program to compute the distance from the center of the first (more massive) body to the barycenter: r1 = a m2 / (m1 + m2).
    Here are a few examples. Masses are in earth-mass units, distances are in kilometers.

     

    Earth-moon: m1 = 1, m2 = .0123, a = 384,000, r1 = 4,670, R1 = 6,380.

    Pluto-Charon: m1 = .0021, m2 = .000254, a = 19,600, r1 = 2,110, R1 = 1,150.

    Sun-Earth: m1 = 333,000, m2 = 1, a = 150,000,000, r1 = 449, R1 = 696,000.

    Note that if r1 is less than the radius of the first body R1, then the barycenter lies within the first body.

  29. Poison parentheses. Find a legal Java expression that leads to a compile-time error when you add parentheses around a subexpression to to document the order of evaluation that would take place in their absence.
    Solution: The literal value 2147483648 (2^31) is permitted only as an operand of the unary minus operator, i.e., -2147483648. Enclosing it in parentheses, i.e., -(2147483648), leads to a compile-time error. Similar ideas with the literal value 9223372036854775808L (2^63).
  30. Car loan payments. Write a program CarLoan.java that reads in three command-line arguments P, Y, and R and calculates the monthly payments you would have to make over Y years to pay off a P dollar loan at R per cent interest compounded monthly. The formula is The formula is
                     P r 
    payment =  ---------------,  where n = 12 * Y, r = (R / 100) / 12
               1  - (1 + r)^(-n)
    

    Caveat: in Chapter 9, we will consider more accurate ways to compute this quantity, so before you go off to run an online bank, be sure to learn about roundoff error.

  31. Write a program Trig.java to illustrate various trigonometric functions in the Math library, such as Math.sin()Math.cos(), and Math.toRadians().

Copyright © 2000–2019 Robert Sedgewick and Kevin Wayne. All rights reserved.



/******************************************************************************
 *  Compilation:  javac Quadratic.java
 *  Execution:    java Quadatic b c
 *  
 *  Given b and c, solves for the roots of x*x + b*x + c.
 *  Assumes both roots are real valued.
 *
 *  % java Quadratic -3.0 2.0
 *  2.0
 *  1.0
 *
 *  % java Quadratic -1.0 -1.0
 *  1.618033988749895
 *  -0.6180339887498949
 *
 *  Remark:  1.6180339... is the golden ratio.
 *
 *  % java Quadratic 1.0 1.0
 *  NaN
 *  NaN
 *
 *
 ******************************************************************************/

public class Quadratic { 

    public static void main(String[] args) { 
        double b = Double.parseDouble(args[0]);
        double c = Double.parseDouble(args[1]);

        double discriminant = b*b - 4.0*c;
        double sqroot =  Math.sqrt(discriminant);

        double root1 = (-b + sqroot) / 2.0;
        double root2 = (-b - sqroot) / 2.0;

        System.out.println(root1);
        System.out.println(root2);
    }
}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. Last updated: Fri Oct 20 14:12:12 EDT 2017.

Built-in: Wind Chill + Scanner + Math.random()

 

Screen Shot 2014-09-09 at 10.24.34 PM

  1. Wind chill.
    Given the temperature t (in Fahrenheit) and the wind speed v (in miles per hour), the National Weather Service defines the effective temperature (the wind chill) to be:

screen-shot-2016-09-20-at-8-46-04-am

screen-shot-2016-09-20-at-9-02-54-am

Write a program WindChill_YI.java that takes two double command-line arguments t and v and prints the wind chill. Use Math.pow(a, b) to compute ab.
Note: the formula is not valid if t is larger than 50 in absolute value or if v is larger than 120 or less than 3 (you may assume that the values you get are in that range).

Resources for some of these assignments:

[spoiler title=’Math.random()’]
/**
 * An itty bitty program to learn about Math.random()
 * GE
 * 9/28/2017
 * 
 */
public class MathRandTest_GE
{
   public static void main(String []args)
   {
       for (int i = 0; i < 100; i++)
        {
            System.out.println(Math.random());
        }

    }
}

[/spoiler] [spoiler title='Scanner Class']
/**
 *  good resource: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html
 * @author gracielaelia
 * Problem: Both hasNext and next methods may block waiting for further input.
 * hasNext() doesn't return false ever!!!! next() blocks until something is input!
 * As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), 
 * or at the end of the file if you use < style redirection.
 * You cannot easily send and EOF character using the keyboard"
 * -- usually Ctrl+D on Linux/Unix/Mac 
 * or Ctrl+Z on Windows does it
 */   
import java.util.Scanner;

public class ScannerTest_GE{
    public static void main(String [] args)
    {
        Scanner scan = new Scanner(System.in);
        String name;     // just a declaration
        double base, exponent;
        System.out.println("Enter the base ");
        base = scan.nextDouble();
        System.out.println("Enter the exponent ");
        exponent = scan.nextDouble();
        System.out.println("Enter your name ");
        name = scan.next();
        System.out.println(name + " the value is " + Math.pow(base,exponent));
        System.out.println(name + " the integer value is " + (int)Math.pow(base,exponent));
    }
  
} 
[/spoiler]

Conditionals: if if/else flowcharts

New topic: Conditionals
Click on this label:
Screen Shot 2014-10-02 at 10.05.29 AM

Classwork:
Flowcharts: write a short code fragment for each of the following flowcharts:
if and if/else
flowchars-if-else

while and for loops

flowchart-loop

More on conditionals with the slides on this link:

Assignments:

  1. Write a more general and robust version of ComplexRootsQuad.java that prints the roots of the polynomial ax^2 + bx + c, prints real and complex solutions.
  2. What (if anything) is wrong with each of the following statements?
    if (a > b) then c = 0;
    if a > b { c = 0; }
    if (a > b) c = 0;
    if (a > b) c = 0 else b = 0;
  3. Write a code fragment that prints true if the double variables x and y are both strictly between 0 and 1 and false otherwise.
  4. Write a program AllEqual_YI.java that takes three integer command-line arguments and prints equal if all three are equal, and not equal otherwise.
  5. Rewrite TenHellos.java to make a program ManyHellos_YI.java that prompts the user for the consecutive lines to print… You may assume that the argument is less than 1000. Hint: consider using i % 10 and i % 100 to determine whether to use “st”, “nd”, “rd”, or “th” for printing the ith Hello.Example output:
    * Starting number? 4
    * Ending number? 8

    * 4th Hello
    * 5th Hello
    * 6th Hello
    * 7th Hello
    * 8th Hello

  6. What is the value of m and n after executing the following code?
    int n = 123456789;
    int m = 0;
    while (n != 0) {
       m = (10 * m) + (n % 10);
       n = n / 10;
    }
    
    
  7. What does the following code print out?
    int f = 0, g = 1;
    for (int i = 0; i <= 15; i++) {
       System.out.println(f);
       f = f + g;
       g = f - g;
    }
    
    

A site to check your understanding:


Conditionals: Ex 1-4

 

Classwork:

  1. Write a program YI_FivePerLine.java that, using one for loop and one if statement, prints the integers from 1000 to 2000 with five integers per line. Hint: use the % operator.

  2. Write a program YI_FunctionGrowth.java that prints a table of the values of ln n, n, n ln n, n^2, n^3, and 2^n for n = 16, 32, 64, …, 2048. Use tabs (‘\t’ characters) to line up columns.

Homework:

  1. What is the value of m and n after executing the following code?

int n = 123456789;
int m = 0;
while (n != 0) {
   m = (10 * m) + (n % 10);
   n = n / 10;
}

  1. What does the following code print out?

int f = 0, g = 1;
for (int i = 0; i <= 15; i++) {
   System.out.println(f);
   f = f + g;
   g = f - g;
}

Conditionals: Ex 1-7

Screen Shot 2014-09-23 at 10.00.31 AM

Classwork:
1. Write a more general and robust version of YI_Quadratic.java that prints the roots of the polynomial ax^2 + bx + c, prints an appropriate error message if the discriminant is negative, and behaves appropriately (avoiding division by zero) if a is zero.

  1. What (if anything) is wrong with each of the following statements?
    if (a > b) then c = 0;
    if a > b { c = 0; }
    if (a > b) c = 0;
    if (a > b) c = 0 else b = 0;

  2. Write a code fragment that prints true if the double variables x and y are both strictly between 0 and 1 and false otherwise.

Homework: Conditionals and loops
4. Write a program YI_AllEqual.java that takes three integer command-line arguments and prints equal if all three are equal, and not equal otherwise.

  1. Rewrite YI_TenHellos.java to make a program YI_Hellos.java that takes the number of lines to print as a command-line argument. You may assume that the argument is less than 1000. Hint: consider using i % 10 and i % 100 to determine whether to use “st”, “nd”, “rd”, or “th” for printing the ith Hello.

  2. What is the value of m and n after executing the following code?

int n = 123456789;
int m = 0;
while (n != 0) {
   m = (10 * m) + (n % 10);
   n = n / 10;
}

  1. What does the following code print out?
int f = 0, g = 1;
for (int i = 0; i <= 15; i++) {
   System.out.println(f);
   f = f + g;
   g = f - g;
}

Conditionals: Simple Interest

Screen Shot 2014-09-23 at 10.00.31 AM

Write a program, SimpleInterest_YI.java that uses a while loop to calculate how many years it would take to have at least $1,100 at an interest rate of 1.2% when $1,000 is deposited in a savings bank account. DO NOT USE THE FORMULA.

stack-of-money

Simple interest is money you can earn by initially investing some money (the principal). A percentage (the interest) of the principal is added to the principal, making your initial investment grow!

As part of your program include the calculation done with the formula.

An example of Simple Interest

Conditionals: Even Fib Numbers

screen-shot-2016-10-27-at-8-36-29-am

Project Euler
Even Fibonacci numbers
Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Write a java program, EvenFibPE2_YI.java to solve this problem.

Conditionals: 1000 digit Number

 

screen-shot-2016-10-27-at-8-36-29-am

Project Euler Problem 8

Largest product in a series
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450

Write a java program, ThirteenAdj_YI.java to find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

NOTE: Here is the code to handle the 1000-digit number

String adjStrNumbers = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
System.out.println("The length of this number is " + adjStrNumbers.length());
//The length of this number is 1000

Check what this code snippet does:

for ( int i = 0; i < 20; i++)
System.out.print( Integer.parseInt( adjStrNumbers.substring(i,i+1) ) );


WARNING:
The largest product of thirteen adjacent digits is 23514624000 if you declare the variables for product and largest of type “long”. Otherwise, when using type “int”, the largest product of thirteen adjacent digits is 2091059712 if you use int for x and product!!!!!!!!! THIS IS THE WRONG ANSWER