4.12 Exercise: Even and Odd Numbers

So here's an exercise for you. I want you to write a function called displayNumber that takes a parameter called limit. So we pass a number in here, like 10, and when we call this function, we need to call all the numbers from 0 to the number we provided as the limit. Now If this number is even, we should display the even number, otherwise we should display odd. This is a fairly easy exercise. Pause the video, and when you're done, continue watching the correction. So here we need a for loop, we set our variable i to 0, and as long as i is less than or equal to this limit, we'll run this loop, and on each iteration, we'll increment i. Now, here we need to check whether i is an even number or not. So, if i modulo 2 = 0, we display i on the console, and as a second argument we pass an EVEN, so even, otherwise we do a console. log of i and as a second argument we pass an ODD, so odd. Now there is another way to write this program, so instead of having to separate the console. log instructions, we can do something like this. We can declare a constant, called message, and here we can use the conditional operator. So if i is an even number, we set the message to even, otherwise we set it to odd. Then we make a console. Log of i and message. This second implementation is a little bit cleaner, but if you use the first implementation, that's fine too. Now save the changes, we get all the numbers, from 0 to 10. That's it for this little fix, let's get together for a very next demonstration.