target = 10;
found = false;
location = -1;
for k = 1:50
value = randi([-20 20]); % generate one random integer
if value == target
found = true;
location = k;
break
end
end
if found
fprintf('The number %i was found on iteration %i\n', target, location)
else
fprintf('The number %i was not found in 50 trials\n', target)
end
This patternβtest a condition, then exit early with breakβis useful whenever you want to stop searching once you find what you need.
π Example41.Example: Skipping Multiples with continue.
Sometimes you want to skip certain iterations in a loop without exiting early. The continue command jumps to the next iteration immediately, skipping any remaining code in the current iteration.
When num is 3, 6, or 9, the continue command skips the fprintf statement and moves directly to the next value. This is cleaner than nesting the print statement inside an else block.
π§π»βπ» Class Activitiesπ§π»βπ» Class Activities
These activities will help you practice using loops to solve interesting problems. Each activity requires only loops, variables, and basic arithmeticβno arrays needed.
Write a MATLAB script with a for-loop from 1 to 20 that adds the loop index (1..20) to a running total (for example, stored in a variable total). Use an if-statement with mod and continue so that values divisible by 3 are skipped.
Use a while-loop to generate random integers with randi([1, 10]). Keep a trial counter and use an if-statement with break to stop as soon as the value is 7.
Write a function named find_first_multiple_of_six that loops through integers from 1 to limit. Inside the loop, use an if-statement and return to stop immediately when the first multiple of 6 is found.
Update your function so that it returns -1 if no value in the loop meets the condition. Test with a small limit and a larger limit to confirm both outcomes.