COS 126

Conditionals and Loops
Programming Assignment

Due: 11:55pm

The goal of this assignment is to write five short Java programs to gain practice writing expressions, loops, and conditionals.

  1. Type conversion. There are a number of different formats for representing color. RGB format specifies the level of red (R), green (G), and blue (B) on an integer scale from 0 to 255: It is the primary format for LCD displays, digital cameras, and web pages. CMYK format specifies the level of cyan (C), magenta (M), yellow (Y), and black (K) on a real scale of 0.0 to 1.0: It is the primary format for publishing books and magazines. Write a program RGBtoCMYK.java that reads in three integers red, green, and blue from the command line and prints out equivalent CMYK parameters. The mathematical formulas for converting from RGB to an equivalent CMYK color are:
    RGB to CMYK formula

    Hint. Math.min(x, y) returns the minimum of x and y.

    % java RGBtoCMYK 75 0 130       // indigo
    cyan    = 0.4230769230769229
    magenta = 1.0
    yellow  = 0.0
    black   = 0.4901960784313726
    
    If all three red, green, and blue values are 0, the resulting color is black (0 0 0 1).

  2. Distinct values. Write a program Distinct.java that takes three integer command line parameters a, b, and c and prints out the number of distinct values (1, 2, or 3) among a, b, and c.
    % java Distinct 876 5309 5309
    There are 2 distinct values
    
    % java Distinct 17 17 17
    There is 1 distinct value
    
    

  3. Average value. Write a program Average.java that takes an integer N as a command line argument and uses Math.random() to generate N random numbers betwen 0.0 and 1.0, and then prints their average value. Use a while loop. Do not print all the numbers. Only print the average. What do you expect the average to approach when N is large?
    % java Average 5
    0.5920401639695192
    

  4. Checkerboard. Write a program Checkerboard.java that reads an integer, N from the command line, and prints out a two dimensional N-by-N checkerboard pattern with alternating spaces and asterisks, like the following 4-by-4 pattern. Use two nested for loops.
    % java Checkerboard 4
    * * * *
     * * * *
    * * * *
     * * * *
    

  5. Ordinals. Write a program Ordinals.java that takes a command line argument N and prints out the first N ordinals, followed by Hello.
    % java Ordinals 22
    1st Hello
    2nd Hello
    3rd Hello
    4th Hello
    5th Hello
    ...
    10th Hello
    11th Hello
    12th Hello
    13th Hello
    ...
    20th Hello
    21st Hello
    22nd Hello
    
    
    Hint: consider using (i % 10) and (i % 100) to determine when to use "st", "nd", "rd", or "th" for printing the ith Hello.