Request: Good examples of loops (not in a list) for teaching

Hi All

I'm looking for good examples for teaching For and While loops, but without using a list of objects. (I already have those). The problem is that most of the examples I have seen in programming books are inane, like, how to write:
[and three asterisks, which I can't display here, because the interface changes three asterisks into line]

etc. Or how to change every send letter in a string to Upper Case.

Hello? Who would ever want to do that in real life?

I mean, it's nice to initially demonstrate it, but I would like a loop that has an obvious and valuable application to that students can see the value of it.

Bonus if the example is related to Medical/Health Sciences, but it does not have to be.

(A "problem" with App Inventor is lists of objects are so useful, I almost never use other loops, but students do need to know the basics, and I want to give them exercises that are more useful than writing asterisks on a screen :smirk:).


I did :grin:

The Sieve of Eratothsenes is a good loop example.

It hunts for prime numbers.

Oh wait, that also uses a list.

Maybe just hunt for prime numbers with two nested loops, and watch the phone go into a coma.

We get a bunch of posts from people who have used loops for timing in Arduino code, then make the mistake of trying that on a phone only to see their phone lock up.

You need something to loop over.

Maybe throw some Diophantine Equations at them to solve?

Those are Equations that require integer solutions.

If you can express puzzle states without a list, you could try search for a solution to the puzzle of the farmer crossing a river with a goose,fox,and bag of corn in a row boat that can only carry one item at a time.

If left alone,

The fox eats the goose,

The goose eats the corn.

1 Like

My final idea...

Public key cryptography depends on knowing the prime factors of large numbers.

Pick a couple of three digit prime numbers, and assign their product to the students to factor. Don't tell them the prime numbers.

Tell them some bologna about it being your locker combination that you forgot.

As an example of a FOR loop: the user enters the frequency of taking a medication, the starting time of the medication and the number of times the medication should be taken. Then, in coordination with a clock, establish the time of taking the following doses.

@Selim_Tezel @robert_parks may have some ideas, but I think the main challenge is that most real-world problems that need solving outside of pure mathematics tend to require manipulating sets of objects, which naturally lead to solutions that use lists or dictionaries to represent the data.

Doing something graphically might be a way to do it plus being visually appealing (mostly because the graphics system works at the pixel/numeric level). For example, you can write a procedure to draw a regular polygon with N sides on a Canvas. This requires a little bit of trigonometry so you may need to hand wave that bit depending on the target audience.

Note that I used all local variables in the version above but one could make some or all variables global depending on whether local variables have been introduced.

A possible follow up discussion could occur around what happens as the number of sides approaches infinity and why they think that is.

Thanks, all, for your useful suggestions - given me some interesting ideas.

In the meantime, I also asked ChatGPT for ideas and pseudo-code, and this is what it gave me [I can't get the indenting, but I'm sure it can still be understood]:

Calculating Average Heart Rates (FOR Loop)
Description: Calculate the average heart rate from a series of recorded heart rate values.
heartRates = [72, 75, 78, 80, 73] // Example heart rate values
total = 0
for rate in heartRates:
total += rate
average = total / length(heartRates)

Monitoring Patient Temperature (WHILE Loop)
Description: Monitor a patient's temperature until it falls within a normal range.
currentTemp = getCurrentTemperature()
while currentTemp > 37.5 or currentTemp < 36.5:
wait(30) // wait for 30 minutes before rechecking
currentTemp = getCurrentTemperature()

Generating a Medical Record Report (FOR Loop)
Description: Create a report summarizing patient medical records, including patient ID and diagnosis.
patientRecords = getPatientRecords() // Assume each record contains patientID and diagnosis
for record in patientRecords:
print("Patient ID:", record.patientID, "Diagnosis:", record.diagnosis)

Validating Drug Dosage Levels (FOR Loop)
Description: Check a list of drug dosages to ensure they are within a safe range.
drugDosages = [50, 75, 100, 150] // Example dosage values in mg
for dosage in drugDosages:
if dosage < 50 or dosage > 150:
alert("Dosage out of safe range:", dosage)

Automated Patient Follow-Up (WHILE Loop)
Description: Send follow-up reminders to patients until they confirm their upcoming appointment.
appointmentList = getAppointments()
for appointment in appointmentList:
confirmationReceived = False
while not confirmationReceived:
wait(24) // wait for 24 hours
confirmationReceived = checkConfirmation(appointment.patientID)

So chatGPT doesn't know You Can't Wait in AI2

Well, although I told it that I was using MIT App Inventor, I focused on the description and pseudo-code. That will be an interesting thing to discuss with my students :slight_smile:

It also is not avoiding the use of lists well.

Another challenge that is worth noting is that often a lot of low level operations that would require the use of iteration in some form tend to be encapsulated in higher order blocks in App Inventor. You could for example iterate over a list of values to compute the average, but you can also just as well use:

which expresses the idea behind the calculation rather than having to write the calculation itself and work backward as to what it's achieving.

Yes, I saw that. My main concern was to use it is scenarios other than lists of objects. I also then asked it for usage without lists. It gave me these below. Some tweaking required, but my main thing was ideas, so that’s ok. (No more “Write a loop to place asterisks on the screen :slight_smile:

Calculating a Dose Reduction Over Time (FOR Loop)
Description: Gradually reduce a medication dose over a period of days.
initialDose = 100 // Initial dose in mg
reductionRate = 10 // Reduction rate per day in mg
for day in range(1, 11): // Over 10 days
currentDose = initialDose - (reductionRate * day)
print("Day", day, ": Dose =", currentDose, "mg")

Patient Check-in Reminder System (WHILE Loop)
Description: Remind a nurse to check in on a patient every hour for 24 hours.
hours = 0
while hours < 24:
wait(1 hour)
hours += 1

Calculating Compound Interest (FOR Loop)
Description: Calculate compound interest for a medical equipment investment over several years.
principal = 10000 // Investment amount in dollars
interestRate = 0.05 // Annual interest rate
years = 5
for year in range(1, years + 1):
principal *= (1 + interestRate)
print("Year", year, ": Amount =", principal)

Monitoring Radiation Exposure (WHILE Loop)
Description: Monitor and log radiation exposure during a medical procedure until a maximum limit is reached.
maxExposure = 5.0 // Maximum safe exposure level
currentExposure = 0.0
while currentExposure < maxExposure:
currentExposure += measureRadiationExposure()
if currentExposure >= maxExposure:
alert("Maximum exposure limit reached")

Generating a Series of Appointment Times (FOR Loop)
Description: Generate a schedule of appointment times for a clinic day, with appointments every 30 minutes.
startHour = 9 // Clinic starts at 9 AM
endHour = 17 // Clinic ends at 5 PM
for hour in range(startHour, endHour):
for minute in [0, 30]:
print("Appointment time:", formatTime(hour, minute))

Yes, sometimes, I need the students to learn the mechanics, so I'll show them useful functions afterward. But, sometimes, well...a "disadvantage" of MIT App Inventor is that there are so many useful functions, and new ones appearing. Over the years, a number of times, I have taught students how to do things, and then one of them pops up and says "So, why don't you rather just use this this function?" Oh. Dang.

I've learned, that, at the beginning of the course, I explain to my students that MIT App Inventor gets updated, and new stuff is being added all the time, so, if they spot an easier way of doing things, they should let me know. It keeps me on my toes :slight_smile: