Skip to content

Exercises 2 ​

Use your favorite editor or IDE to solve the following exercises. Afterward, compare your solutions with the ones in the solutions bundle.

These exercises no longer ask you to declare specific constants or variables. It’s up to you to choose an appropriate way to represent your input data, intermediate, and final results.

Print your results at the end of every exercise.

Exercise 2.1 ​

This exercise uses the same chessboard as Exercise 1.6:

A chess board with number positions, rows, and columns

Given a position on this chessboard, expressed as a row and column number, calculate the next position on the chessboard, also expressed as a row and column number.

You can assume that the next position after 63 is 0 again.

Exercise 2.2 ​

Given the coefficients, a, b, and c of the quadratic equation ax2+bx+c=0, use the following formulas to calculate the solutions x1 and x2 for this equation:

x1=βˆ’b+b2βˆ’4ac2ax2=βˆ’bβˆ’b2βˆ’4ac2a

Take into account the different number of solutions (0, 1, or 2), depending on the sign of b2βˆ’4ac.

Exercise 2.3 ​

Add parentheses to the following Boolean expression. The parentheses should show the order in which the Boolean operators are applied and should not change the value of the expression:

swift
b1 && b2 || b1 && !b2 && b3

Here, b1, b2, and b3 are variables of type Bool.

Tip

&& and || are left-associative.

Exercise 2.4 ​

Given the current month and year, calculate the number of days in this month. Don’t forget about leap years.

Exercise 2.5 ​

Given a number, determine if this number is a power of 2.

Exercise 2.6 ​

Print a table of the first ten powers of 2. Calculate these powers without using a function.

Exercise 2.7 ​

Given a positive number n, calculate the nth Fibonacci number.

Exercise 2.8 ​

Given a positive number n, calculate the factorial of n.

Exercise 2.9 ​

Given a number of pips between 2 and 12, calculate the odds of rolling this number of pips using two six-sided dice.