Exercise 3: Lemon, Factor, Parity, Nine, HDB
Deadline
This is an ungraded exercise designed to expose you to different patterns of using loops. There is no deadline, but we encourage you to complete it before Thursday's lab so that you do not fall behind.
- Completed Exercise 1.
Learning Outcomes
Be comfortable writing simple C programs that involve loops, including
- a loop with conditional body and counting
- a loop with early return
- a loop that steps through digits in a number
- nested loops
Grading
This exercise is not graded.
Question 1: Lemon
A \((l,m,n)\)-run (also known as a lemon run) is a sequence of \(m\) integers (\(m \ge 1\)) with a gap of \(n\) between one number and the next, starting with \(l\), i.e., \(\langle l, l+n, l+2n, ..., l+(m-1)n \rangle.\)
Write a program called lemon
that reads in three integers \(l\), \(m\), and \(n\) from the standard input, and prints to the standard outputs, the numbers in the \((l, m, n)\)-run, one number per line.
Sample Runs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Question 2: Factor
Given a number \(n\), we want to find out how many factors \(n\) has, excluding the trivial factor 1 and \(n\).
Write a program factor
that reads, from the standard input, a positive integer \(n\), and prints, to the standard output, the factors of \(n\) between 2 and \(n-1\), inclusive).
Sample Runs
1 2 3 4 5 6 7 8 9 |
|
Question 3: Parity
Write a program parity
, that reads from standard input a positive integer \(n\) and prints to the standard output the following two lines,
1 2 |
|
where X
represents the number of odd digits and Y
represents the number of even digits.
Sample Runs
1 2 3 4 5 6 7 8 |
|
Question Credit: Albert Sutiono (cohort 20/21)
Question 4: Nine
Write a program that looks for the least significant occurrence of digit 9 in a given number.
Your program, nine
, should read a positive number from the standard input and print out the position of the least significant occurrence of 9. The rightmost digit has the position of 1, the second last has the position of 2, etc. If the number 9 does not appear in the given number, print 0.
Solve this problem in a function called find_least_significant_9
that takes in a long
parameter (the input number) and returns a long
(the position of 9). Your function should not search through more digits than necessary.
Sample Runs
1 2 3 4 5 6 7 8 9 |
|
Question 5: HDB
ASCII Art refers to the art of drawing with only common letters, numbers, and symbols on our keyboard. My daughter has discovered that, if we draw rows of #
symbols together, the output looks like an HDB flat!
Write a program hdb
that takes in two positive integers \(w\) and \(h\), and draw \(h\) rows of #
symbols, each row containing \(w\) #
, with no spaces before, in between, and after.
Sample Runs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|