Welcome to MATLAB programming! Distinguishing between odd and even numbers is a great starting point. Below are two different ways to implement this: using an if statement and a while loop.
Method 1: Using if Statement
Here’s how you can check if a number is odd or even:
% Define a range of numbers to check
numbers = 1:10; % Example: numbers from 1 to 10
for i = 1:length(numbers)
if mod(numbers(i), 2) == 0
fprintf('%d is even.\n', numbers(i));
else
fprintf('%d is odd.\n', numbers(i));
end
end
Method 2: Using while Loop
This method demonstrates a while loop that processes until all numbers in an array are checked:
% Define the numbers to check
numbers = 1:10; % Example: numbers from 1 to 10
index = 1; % Initialize index
while index <= length(numbers)
if mod(numbers(index), 2) == 0
fprintf('%d is even.\n', numbers(index));
else
fprintf('%d is odd.\n', numbers(index));
end
index = index + 1; % Increment index
end
Key Explanation
-
mod(number, 2):- This function returns the remainder when dividing the number by 2.
- If the result is
0, the number is even. Otherwise, it is odd.
-
fprintf:- Used to display formatted output to the command window.
%dis a placeholder for integers.
Test and Experiment
You can try with different ranges of numbers or even ask the user for input:
% Prompt user for input
num = input('Enter a number: ');
if mod(num, 2) == 0
fprintf('%d is even.\n', num);
else
fprintf('%d is odd.\n', num);
end
Feel free to adapt the code as needed! Let me know if you have additional questions. ????
Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Explore similar technical troubleshooting questions and verified MATLAB solutions: