Swift programming revision for Level 2
Goal
You are going to build a small Swift program that helps a student calculate the area and volume of a room, then the usable volume after furniture is placed inside. This task revises loop and conditional structures, including the for loop, the while loop, and the if statement.
Part 1: Room dimensions
Copy these values into your program. These are the room dimensions in metres.
let roomLength = 6.0
let roomWidth = 4.5
let roomHeight = 2.7
Part 2: Area of the room
Calculate the floor area. Area = length × width.
Calculate the area using roomLength and roomWidth. Print the area with m².
Example output:
Room area: 27.0 m²
Part 3: Ask the user for dimensions (if let)
Ask the user to enter the room length, width, and height. Use if let to cast the input to Double.
Use readLine() to get each value. Use if let to safely convert the input to Double. If the cast fails, print Invalid number.
Starter code:
print("Enter room length:")
if let input = readLine(), let length = Double(input) {
// store length, do further calculations
}
Part 4: Volume of the room
Calculate the full volume. Volume = length × width × height.
Calculate the volume using all three dimensions. Print the volume with m³.
Example output:
Room volume: 72.9 m³
Part 5: Furniture volumes (for loop)
Copy this array into your program. Each value is the volume of a furniture item in cubic metres.
let furnitureVolumes = [1.2, 0.8, 2.5, 0.6, 1.0]
Use a for loop to print each item as Item 1, Item 2, and so on. In the same loop, add each item's volume to a total.
Example output:
Item 1: 1.2 m³
Item 2: 0.8 m³
Item 3: 2.5 m³
Item 4: 0.6 m³
Item 5: 1.0 m³
Part 6: Check for oversized items (if inside loop)
Inside your for loop, add this check.
If any item is larger than 2.0 m³, print Oversized item detected.
Part 7: Usable room volume
Calculate the usable volume. Usable volume = room volume − total furniture volume.
Subtract the total furniture volume from the room volume. Print the usable volume with m³.
Example output:
Usable volume: 66.8 m³
Part 8: Input validation (while loop)
Use a while loop to ensure a valid height is entered. Heights must be greater than 0.
Start with var heightInput = -1.0. Use a while loop to keep asking for a new height until it is greater than 0. After the loop, print the accepted height.
Example output:
Enter height: -2
Enter height: 0
Enter height: 2.4
Accepted height: 2.4 m
Part 9: Final summary output
At the end, print the room area, room volume, total furniture volume, usable volume, and whether usable volume is below 60 m³, with a warning if it is.
Example format:
Room area: 27.0 m²
Room volume: 72.9 m³
Furniture volume: 6.1 m³
Usable volume: 66.8 m³
Usable volume is fine.