HackerRank’s 30 Days of Code: Day 2

Anna Litvinskaya
2 min readJun 13, 2017

--

Somehow, I couldn’t get to the third task for several days, mostly because the previous task felt to be somewhat intimidating for me and required a bit too much googling (and stackoverflowing) for an elementary-level challenge. So, even though I solved it eventually, I felt helpless and not quite up even to the easiest things in programming.

And guess what, I solved the challenge in about half an hour. The code required only a couple of tweaks before it was fully functional!

I went about solving the challenge in a really slow, step-by-step manner. First, I declared the variables from the description of the task: mealCost, tipPercent, and taxPercent. Then, I proceeded to getting the input and saving it to these variables. Next came printf(), as I considered making the required calculations inside of it. I soon realised that it would be very confusing and it was better to make the calculations separately (besides, the description spoke of a new variable, totalCost), so I added three more variables after the already existing three: tip, tax, and totalCost. The calculations section came last (but not least). After this, the code was almost ready and working, and, as I said, required only a couple of tweaks. Here’s the code, and I’ll explain the tweaks below it:

// declaring variables
double mealCost;
int tipPercent;
int taxPercent;
double tip;
double tax;
int totalCost;

// reading user’s input and saving to the variables
scanf(“%lf”, &mealCost);
scanf(“%i”, &tipPercent);
scanf(“%i”, &taxPercent);

// calculating total cost
tip = mealCost * tipPercent / 100;
tax = mealCost * taxPercent / 100;
totalCost = round(mealCost + tip + tax);

// calculating and printing the result
printf(“The total meal cost is %i dollars.”, totalCost);

So, the tweaks:

  1. At first, I wrote tip = mealCost * (tipPercent / 100); and tax = mealCost * (taxPercent / 100); That didn’t work; I removed the brackets (after all, arithmetically speaking, they were unnecessary), and it worked.
  2. Being a JavaScript fan, I tried to use Math.round on totalCost, but, fortunately, decided to check if C required something else for rounding numbers. Sure it did.
  3. You know this feeling when you spend hours debugging your code before discovering that it was a silly missing semicolon causing all the woe? Well, I forgot the comma in the output, so my printf() gave “The total meal cost is 15 dollars” instead of the expected “The total meal cost is 15 dollars.” But I was lucky to notice it almost immediately :)

--

--