Odd and even numbers

Illustration
Ahmed Nasrullah - 2023-08-16T12:44:45+00:00
Question: Odd and even numbers

Hi I'm new in matlab so i need a little help to get started. How do i make a program which can distinguish from odd and even numbers? I know that i need to make a loop, it should be either if or while but i would love some suggestions on how to solve this problem. Thanks :)

Expert Answer

Profile picture of Neeta Dsouza Neeta Dsouza answered . 2025-11-20

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

  1. 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.
  2. fprintf:

    • Used to display formatted output to the command window.
    • %d is 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. ????


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!