Java Code Challenges: Loops Not Involving Traversal

Try some code challenges involving loops

In these code challenges, we’ll practice our loops! Some of these challenges are difficult, so make sure you take some time to outline your solution before writing out your code.

If you get stuck, look at your output and check your assumptions to try to find where you’re going wrong, and iterate on your solution. Good luck!

Loop Refresher

Loops are an incredibly useful tool to repeat certain actions without needing to define the action more than once. They can do things like solving for a number, combining multiple strings, populating an array with several numbers, and much more.

For example, say we were ordering at a restaurant that sells burritos and had $4267 in our wallet. One vegetarian burrito costs $7 (including tax). We could whip up a script to figure out how many we can order:

public class BurritoCalculator{ public static int getBurritoQuantity(int burritoCost) { int budget = 4267; int numBurritos = 0; while (budget >= burritoCost) { numBurritos++; budget -= burritoCost; } return numBurritos; } public static void main(String []args){ int burritoCost = 7; System.out.println(getBurritoQuantity(burritoCost)); } }

Here, we start with 0 burritos. We can use this numBurritos variable to keep track of the total number of burritos we can purchase. Every time we add another burrito to purchase, we will want to subtract the cost of the burrito from our total budget, and do this until we don’t have any more left for a burrito.

Instead of writing these two lines over and over, we can use a loop to repeat these steps for us. These steps will continue to run as long as the condition remains true, so our condition to stop when we no longer have any money left for a burrito.

1. Leftover Funds

Now you might wonder: “This means I will have money left over, but I want to use all my money.” How can we tweak .hasLeftoverFunds() to give us that information?