The While Loop
How I used one to solve an actual life question
Being in software engineering, specifically the job search, one is inundated with algorithmic problems. While there are many great tools out there for practicing, most of the problems aren’t super prevalent in everyday life. Meaning, those specific problems would never happen to me. There could be many reasons for my thinking this, primarily, my exposure to the actual engineering work place is very low, and these types of things haven’t been my norm. Or, I’ve never needed to reverse a string or find valid parenthesis in real life.
Don’t get me wrong. I understand that most of these problems are very much specific to working with data in a way that would never happen in real life. But, this is the reason why I was so surprised to be able to use a while loop to solve a real world question.
The Set Up
I was talking to a friend, and she asked me “If I make x amount of money now, and I get an annual raise of y percent, how many years will it take for me to make z amount?”
I thought, that’s kind of a lot of math to do, but then realized, I could write a loop to solve this! Since I knew I wanted to solve a problem based on a condition being true rather than a set amount of times, I thought the while loop would be my jam. For more information on the while loop, check out the MDN docs.
The problem: given a starting salary and an annual 1.5% raise, how many years will it be before a new desired salary is reached?
The first thing I did was create a function and declare the variables for current and desired salary.
Next, add in the meat and potatoes while loop.
And, to top it off, return the years variable to produce the answer. Putting the function in the console should reveal the answer.
There are everyday uses for these types of coding resources/tools. If we keep our ears and eyes open, we might just find a way to use our skillset to help solve some very real and relevant problems!