Java Reference
In-Depth Information
2.8 Exercises
Exercise 2.1 (Integer parity)
Write a program that interactively asks for an integer at the console
and reports its odd/even parity. Modify the code so that the program
first asks the user how many times it would like to perform parity
computations, and then iteratively asks for a number, compute its parity,
and repeat until it has performed the required number of parity rounds.
Further modify this program so that now both input and output are
redirected into text files, say input.txt and output.txt .
Exercise 2.2 (Leap year)
A leap year is a year with 366 days that has a 29th February in its
calendar. Years whose division by 4 equals an integer are leap years
except for years that are evenly divisible by 100 unless they are also
evenly divisible by 400. Write a program that asks for a year and report
on whether it is a leap year or not. Modify this code so that the program
keeps asking for years, and compute its leap year property until the user
input
1.
Exercise 2.3 (Displaying triangles)
Write a program that asks for an integer n , and write on the output a
triangle as illustrated for the following example (with n = 5):
1
12
123
1234
12345
1234
123
12
1
Exercise 2.4 (Approximating a function minimum)
25
x
3
Let f ( x )=sin(
[0 ] be a given function. Write a
program that takes as argument an integer n and returns the minimum
of f ( x ) on the range x
4 x +6 )
for x
x 2
1
n . Execute the
program for n = 10, n = 100 and n = 100000 and check that the root is
about
[0 ] evenly sampled by steps
1 . 84318.
Exercise 2.5 (Computing a numerically)
1
a
Consider Newton's root finding method to compute
by choosing
1
x 2 . Show that we obtain the following sequence:
function f ( x )= a
 
 
Search WWH ::




Custom Search