Splitting The Bill
Part of the Fundamentals section of Coddy's Swift journey — lesson 40 of 86.
Challenge
EasyIn the previous lesson, you calculated the tip amount and total with tip. Now, add the final calculation to determine how much each person pays when splitting the bill.
Using the totalWithTip you already calculated and the numberOfPeople, calculate the amount each person should pay by dividing the total by the number of people.
Remember to convert numberOfPeople from Int to Double before performing the division.
Update your output to print in this exact format:
Welcome to the Bill Split Calculator!
Bill: [billTotal]
Tip: [tipPercentage]%
People: [numberOfPeople]
Tip amount: [tipAmount]
Total with tip: [totalWithTip]
Each person pays: [amountPerPerson]For example, if the inputs are 100.0, 20, and 4, the output should be:
Welcome to the Bill Split Calculator!
Bill: 100.0
Tip: 20%
People: 4
Tip amount: 20.0
Total with tip: 120.0
Each person pays: 30.0Try it yourself
print("Welcome to the Bill Split Calculator!")
if let billInput = readLine(), let billTotal = Double(billInput) {
if let tipInput = readLine(), let tipPercentage = Int(tipInput) {
if let peopleInput = readLine(), let numberOfPeople = Int(peopleInput) {
let tipAmount = billTotal * Double(tipPercentage) / 100
let totalWithTip = billTotal + tipAmount
print("Bill: \(billTotal)")
print("Tip: \(tipPercentage)%")
print("People: \(numberOfPeople)")
print("Tip amount: \(tipAmount)")
print("Total with tip: \(totalWithTip)")
}
}
}All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input