Coding Exercises: Hello
1. Multiples of 3
Write a program that prints the first 10 multiples of 3.
2. FizzBuzz
Write a FizzBuzz program.
Your program should iterate through the first 30 positive
integers, printing each one. However, if the integer \(n\) is a multiple of 3, print
Fizz
instead of the number. And if \(n\) is a multiple of 5, print
Buzz
instead. And if \(n\) is a multiple of both 3 and 5,
print FizzBuzz
instead.
Sample output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
.
.
.
3. Geometric sequence
Write a program that prints out the first terms of a geometric sequence, i.e. a sequence with a common ratio, for example: 3, 6, 12, 24, 48, …
4. Cubes
Write a program that prints out the cubes of the counting numbers: 0, 1, 8, 27, 64, 125, …
5. Fibonacci sequence
Write a program that prints out the first 30 terms of the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …
Hint: I find it easiest to think about this problem using 3 variables: \(a\) and \(b\) slide up the sequence, and we use a temporary variable \(c\) to help do this.
Challenge: After you’ve done this exercise, try doing it using only 2 variables.
Challenge: Try printing out the ratios of successive terms of the Fibonacci sequence. The sequence of ratios approaches a limit - do you recognize what this limit is?
6. (Challenge) Factorial sequence
Print the first 10 factorials, where the factorial of n (denoted n!) is defined as: \[ n! = 1 \cdot 2 \cdot ... n \]
0! is defined to be 1.
Output:
1, 1, 2, 6, 24, 120, ...
7. (Challenge) Collatz sequence
A Collatz sequence is defined as follows:
The first number is any positive integer.
Subsequent values are calculated by the following rule:
- If n is even, the next number is n / 2
- If n is odd, the next number is 3 * n + 1
Example output:
3, 10, 5, 16, 8, 4, 2, 1, ...
The output will vary based on the first number. However, the Collatz conjecture states that this sequence will eventually cycle 4, 2, 1, independent of the starting value.
Print Collatz sequences with different starting values. Verify that the sequence eventually cycles 4, 2, 1…