Program
Write a program in matlab to check whether the given number is even or odd. Use the function name isevenorodd.Solution
Solution to this example is very simple. Here we will just use very basic concepts to solve this problem. Have a look at the program and if you don't understand any then go to explanation section and if you still don't understand then go to the below links to check the concept( or basics) behind this program. The concepts are as follows:1) Matlab functions
2) if else in matlab
3) rem function in matlab (remainder after division)
4) fprintf in matlab
Program
function isevenorodd(n) %This function will check whether the given number is even or odd and %will print even if the number is even and odd if the number is odd. %Here we are using the remainder function with if else condition statement if rem(n,2) == 0 fprintf('The number is even\n'); else fprintf('The number is odd\n'); end
To download this program in matlab file format then click here: isevenorodd.m(350 Bytes)
Explanation
We will understand this program with an example so that everyone will get it easily. Here I am considering the number 5.
First in the function you will give the input 5 as n.
Now digging deep, the if else statement is started and the condition here to satisfy the if statement is, if the remainder after division with the number 2 is 0 then you can go inside the if statement, otherwise you are not allowed to access the statement inside the if statement, and you will have to check the next condition if there or else go to else. The condition is not satisfied. Now here there is no else if statement and the program will directly reach the else statement. In the else statement there is a fprintf statement to print the output as the number is odd. So finally the output is as follows:
>> The number is odd
>>
The above code was high lighted using hilite.me
Understood the code?? Then run the code on your machine and comment your input and output below in the comments.
Keywords: even, odd, matlab functions, if-else, check