Skip to content

Exercises 1 ​

Use your favorite editor or IDE to solve the following exercises. Afterward, compare your solutions with the ones in the solutions bundle. These solutions are an important part of this course, so study them carefully.

Exercise 1.1 ​

Declare a constant named exercises with an initial value of 10. Declare a variable named exercisesSolved with an initial value of 0. Increment this variable every time you solve an exercise, including this one.

Exercise 1.2 ​

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

swift
5 * 3 - 4 / 2 * 2

Exercise 1.3 ​

Declare two variables, a and b, of type Double and assign values to both. Then, write a piece of code to swap the values of a and b and print the results.

Exercise 1.4 ​

Calculate the average of a and b and store it in a constant named average.

Do you know why it’s important that a and b are of type Double?

Exercise 1.5 ​

A temperature expressed in Β°C can be converted to Β°F by multiplying the temperature by 1.8 and then adding 32. In this exercise, you’ll do the reverse: convert a temperature from Β°F to Β°C.

Declare a constant named fahrenheit and assign it a value. Calculate the corresponding temperature in Β°C and store it in a constant named celsius.

Exercise 1.6 ​

Suppose the squares on a chessboard are numbered left-to-right, top-to-bottom, with 0 being the top-left square and 63 being the bottom-right square. Rows are numbered top-to-bottom, 0 to 7. Columns are numbered left-to-right, 0 to 7:

A chess board with number positions, rows, and columns

Declare two variables, row and column, and assign each a value between 0 and 7. Calculate the corresponding square number and store it in a variable named position.

Next, do the inverse. Assign position a value between 0 and 63. Calculate the corresponding row and column numbers and store them in row and column.

Exercise 1.7 ​

Declare two constants, dividend and divisor, of type Double, and assign both a value. Calculate the quotient and remainder of an integer division of dividend by divisor, and store the results in constants quotient, of type Int, and remainder, of type Double. Calculate the remainder without using the % operator.

Exercise 1.8 ​

A circle is made up of 2Ο€ radians, which correspond with 360 degrees. Declare a constant named degrees and assign it an initial value. Calculate the corresponding angle in radians and store it in a constant named radians.

Exercise 1.9 ​

Declare four constants, x1, y1, x2, and y2, to represent the 2-dimensional coordinates of two points. Use the following formula to calculate the distance (d) between these points:

d=(x2βˆ’x1)2+(y2βˆ’y1)2

Store the result in a constant named distance.

Exercise 1.10 ​

Increment exercisesSolved one final time, then print the percentage of exercises you solved. This should be an integer between 0 and 100.