Programming Assignment
Conditionals, Loops, Arrays
The objective of this task is to compose five brief Java programs to improve proficiency in using loops,
conditionals, and arrays. The aim of this task is to compose five brief Java programs to improve proficiency in
using loops and conditionals.
1. Bits. Write a program Bits.java that takes an integer command-line argument N and
uses a while loop to compute the number of times you need to divide N by 2 until it is
strictly less than 1. Print out the error message "Illegal input" if N is negative.
% java Bits 0 % java Bits 8
0 4
% java Bits 1 % java Bits 16
1 5
% java Bits 2 % java Bits 1000
2 10
% java Bits 4 % java Bits -23
3 Illegal input
Remark: This computes the number of bits in the binary representation of N, which
also equals 1 + floor(log2 N) when N is positive. This quantity arises in information
theory and the analysis of algorithms.
2. Boolean and integer variables. Write a program Ordered.java that reads in three
integer command-line arguments, x, y, and z. Define a boolean variable isOrdered
whose value is true if the three values are either in strictly ascending order (x < y < z)
or in strictly descending order (x > y > z), and false otherwise. Print out the variable
isOrdered using System.out.println(isOrdered).
3. % java Ordered 10 17 49
4. true
5.
6. % java Ordered 49 17 10
7. true
8.
9. % java Ordered 10 49 17
10. false
11. Type conversion and conditionals. Several different formats are used to represent
color. For example, the primary format for LCD displays, digital cameras, and web
pages, known as the RGB format, specifies the level of red (R), green (G), and blue
(B) on an integer scale from 0 to 255. The primary format for publishing books and
magazines, known as the CMYK format, specifies the level of cyan (C), magenta (M),
yellow (Y), and black (K) on a real scale from 0.0 to 1.0.
, Write a program RGBtoCMYK.java that converts RGB to CMYK. Read three integers
red, green, and blue from the command line, and print the equivalent CMYK values
using these formulas:
Hint. Math.max(x, y) returns the maximum of x and y.
% java RGBtoCMYK 75 0 130 // indigo
cyan = 0.423076923076923
magenta = 1.0
yellow = 0.0
black = 0.4901960784313726
If all three red, green, and blue values are 0, the resulting color is black, so you should
output 0.0, 0.0, 0.0 and 1.0 for the cyan, magenta, yellow and black values,
respectively.
12. Checkerboard. Write a program Checkerboard.java that takes an integer
command-line argument N, and uses two nested for loops to print an N-by-N
"checkerboard" pattern like the one below: a total of N2 asterisks, where each row has
2N characters (alternating between asterisks and spaces).
% java Checkerboard 4 % java Checkerboard 5
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * *