🔢 Day 2: Operators – HackerRank Practice with C#

PriyaPriya
2 min read

In this post, we’ll solve a classic HackerRank problem that tests your understanding of basic arithmetic operations, percentages, and rounding in C#. It’s a great warm-up for anyone looking to sharpen their logic-building and syntax skills.

🧠 Problem Statement

You are given:

  • meal_cost – the base cost of a meal

  • tip_percent – the tip percentage

  • tax_percent – the tax percentage

Your task:

Calculate the total cost of the meal by:

  1. Calculating the tip and tax

  2. Adding them to the meal cost

  3. Rounding the result to the nearest whole number

🧾 Real-world analogy: When you're at a restaurant, the final bill includes both tip and tax. For simplicity, it’s often rounded to the nearest integer — especially when paid by card or when splitting the bill.

✅ Steps to Implement

  1. Tip = meal_cost * tip_percent / 100

  2. Tax = meal_cost * tax_percent / 100

  3. Total Cost = meal_cost + tip + tax

  4. Round the result using Math.Round()

  5. Print the rounded value

⚠️ HackerRank Pro Tip: Even a slight deviation in formatting can cause test case failures — avoid unnecessary spaces or blank lines.

💡 C# Code Solution

public static void solve(double meal_cost, int tip_percent, int tax_percent)

{

double tip = meal_cost * tip_percent / 100;

double tax = meal_cost * tax_percent / 100;

double totalCost = meal_cost + tip + tax;

// Round to nearest integer

int roundedTotal = (int)Math.Round(totalCost);

// Print the result

Console.WriteLine(roundedTotal);

}

📌 Sample Input

12.00

20

8

📤 Sample Output

15

🔍 Explanation

  • Tip = 12.00 × 20% = 2.40

  • Tax = 12.00 × 8% = 0.96

  • Total = 12.00 + 2.40 + 0.96 = 15.36

  • Rounded = 15

🧪 Mini Practice

Try solving this on your own:

Meal cost: 10.25

Tip percent: 17

Tax percent: 5

👉 Calculate step-by-step and verify if your final answer is correct!

🎯 Key Takeaways

  • Math.Round() helps in getting the nearest whole number.

  • Always divide by 100 for percentage calculations.

  • Use Console.WriteLine() for exact output formatting.

  • Prepare for edge cases (0 values, negatives, etc.) even if not required.

🧩 What’s Next?

In Day 3, we’ll move into conditionals and logical operators. Stay tuned!

1
Subscribe to my newsletter

Read articles from Priya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Priya
Priya