Problem overview
The method PrintEvenOdd(int n) looks at each number from 0 to n - 1. For an odd number it prints the word odd. For an even number it prints the number itself. It returns nothing, because the result is the console output.
For n = 6 the numbers checked are 0, 1, 2, 3, 4 and 5. The output is:
0
odd
2
odd
4
odd
The number n itself is not included: the range stops one before it.
Approach
Every number gets one of two treatments, so the plan is a loop over the range with an if/else inside it. The loop count is known in advance (n numbers), which makes a for loop the natural choice.
The only real question is how to tell odd from even. The remainder operator % answers it: i % 2 is the remainder of dividing i by 2. It is 0 for even numbers and 1 for odd ones, as long as i is not negative. Here i starts at 0 and only increases, so the remainder is always 0 or 1.
Step by step
- Write the loop. A variable
istarts at 0 and runs whilei < n, which covers 0 up ton - 1. The header usesi++to move on by one. - Handle the odd case. Inside the loop, test
i % 2 == 1. If it is true, print the string"odd". Here the quotes are needed, because the output is the word itself. - Handle the other case. Add an
elsebranch that printsi, without quotes, so that the number is written. Everything that is not odd is even, so no second test is needed.
The solution in C#
class Solution {
public void PrintEvenOdd(int n) {
for (int i = 0; i < n; i++) {
if (i % 2 == 1) {
Console.WriteLine("odd");
} else {
Console.WriteLine(i);
}
}
}
}
Some details worth knowing:
Console.WriteLinehas versions for strings and for integers. In the first branch the argument is astring; in the second it is anint, which is converted to text when written.- Only one branch runs per pass, so each number produces exactly one line.
- The method is
void. It prints, and it does not build or return a list. - The method name
PrintEvenOddand the parameternmust match exactly, since C# is case-sensitive.
Complexity
The loop runs n times and each pass does a constant amount of work, so the time is O(n). Only the counter is stored, so the space is O(1).
Edge cases and common mistakes
- Zero is even.
0 % 2is 0, so the first line of output is the number 0, as in the example. - Using
<=in the loop.i <= nadds an extra line fornitself. - Quotes around
i.Console.WriteLine("i")prints the letter i every time. - Swapping the branches. Printing the number for odd values and the word for even values reverses the output. Check the example: index 0 shows a number, index 1 shows
odd. =instead of==.if (i % 2 = 1)does not compile in C#.n = 0. The loop does not run, and nothing is printed.- Negative numbers. The task does not include them, but note that in C#
-3 % 2is-1, so a test of== 1would miss negative odd numbers. Testingi % 2 == 0for evenness is safe for every integer.
Testing
n = 6prints 0, odd, 2, odd, 4, odd.n = 1prints 0.n = 2prints 0 and odd.n = 0prints nothing.