Calculating Tip And Total
Part of the Fundamentals section of Coddy's Swift journey — lesson 39 of 86.
Challenge
EasyIn the previous lesson, you gathered the bill total, tip percentage, and number of people from the user. Now, add the calculation logic to compute the tip amount and the total bill including the tip.
Using the values you already have, calculate:
- The tip amount: bill total multiplied by the tip percentage divided by 100
- The total with tip: bill total plus the tip amount
Remember to convert the tip percentage from Int to Double before performing the calculation.
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]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.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) {
print("Bill: \(billTotal)")
print("Tip: \(tipPercentage)%")
print("People: \(numberOfPeople)")
}
}
}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