Loops and flow control. Make function called loopTest(N) that loops through the values 1 through N and for each number n it should display ‘n is divisible by 2’, ‘n is divisible by 3’, ‘n is divisible by 2 AND 3’ or ‘n is NOT divisible by 2 or 3’. Use a for loop, the function mod or rem to figure out if a number is divisible by 2 or 3, and num2str to convert each number to a string for displaying. You can use any combination of if, else, and elseif.
时间: 2024-03-10 15:46:26 浏览: 182
Designing Control Loops for Linear and Switching Power Supplies英
Sure, here is the code for the `loopTest` function:
```
function loopTest(N)
%LOOPTEST Loops through the values 1 through N and displays whether each number is divisible by 2, 3, both, or neither.
for n = 1:N
if mod(n, 2) == 0 && mod(n, 3) == 0
disp([num2str(n), ' is divisible by 2 AND 3']);
elseif mod(n, 2) == 0
disp([num2str(n), ' is divisible by 2']);
elseif mod(n, 3) == 0
disp([num2str(n), ' is divisible by 3']);
else
disp([num2str(n), ' is NOT divisible by 2 or 3']);
end
end
end
```
You can call this function with any positive integer `N` to test it. For example, `loopTest(10)` would loop through the values 1 through 10 and display the appropriate message for each number.
I hope this helps! Let me know if you have any questions.
阅读全文