Splitting The Bill
Part of the Fundamentals section of Coddy's R journey — lesson 36 of 78.
Challenge
EasyIn the previous lesson, you calculated the tip amount and total bill. Now, add the final step: splitting the total among all the people.
After displaying the tip amount and total with tip, calculate how much each person should pay by dividing the total by the number of people.
Store this in a variable named per_person.
Then display the final result in the following format:
Each person pays: $[per_person]Use cat() for all output and include newline characters \n where needed.
For example, if the inputs are 100, 20, and 4, the complete output should be:
Welcome to the Bill Split Calculator!
Let's split your bill fairly.
Bill: $100
Tip: 20%
People: 4
Tip amount: $20
Total with tip: $120
Each person pays: $30Try it yourself
# TODO: Write your code below
# Use cat() to display the welcome message
# Remember to use \n for new lines
cat("Welcome to the Bill Split Calculator!\nLet's split your bill fairly.\n")
# Read user inputs
con <- file("stdin", "r")
bill <- as.numeric(suppressWarnings(readLines(con, n = 1)))
tip_percent <- as.numeric(suppressWarnings(readLines(con, n = 1)))
people <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)
# Display confirmation message
cat("Bill: $", bill, "\n", sep = "")
cat("Tip: ", tip_percent, "%\n", sep = "")
cat("People: ", people, "\n", sep = "")
# Calculate tip amount and total
tip_amount <- bill * tip_percent / 100
total <- bill + tip_amount
# Display calculation results
cat("Tip amount: $", tip_amount, "\n", sep = "")
cat("Total with tip: $", total, "\n", sep = "")All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 27Bill Split Calculator
Welcome MessageGetting User Input2Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values