Problem overview
The function print_even_odd takes a positive integer n. For each number from 0 up to n - 1 it prints either the word odd, when the number is odd, or the number itself, when it is even. It returns nothing.
For n = 6 the output is:
0
odd
2
odd
4
odd
The numbers 0 to 5 are visited. The even ones (0, 2, 4) are printed as numbers, and the odd ones (1, 3, 5) are replaced by the word.
Approach
This is the pattern of a loop with a two-way decision inside it. For each i the loop asks one question, whether i is odd, and takes one of two branches. A number is odd when dividing it by 2 leaves remainder 1, which in code is i % 2 == 1. Anything else is even, so an else branch covers it without a second test.
Step by step
- Write the loop
for i in 0..n. A Rust range0..nincludes 0 but excludesn, which matches "from 0 to n - 1" exactly. Writing0..=nwould visitnas well. - Test for odd with
if i % 2 == 1, and print the word withprintln!("odd"). - Handle the even case in an
elsebranch, and print the number withprintln!("{}", i). The{}placeholder is replaced by the value after the format string.
The solution in Rust
impl Solution {
fn print_even_odd(n: i32) {
for i in 0..n {
if i % 2 == 1 {
println!("odd");
} else {
println!("{}", i);
}
}
}
}
The Rust details worth noticing:
- The loop variable is created by the
for. There is noletfori, and nomut, because the loop gives it a fresh value on each pass and you never assign to it. - Ranges are half-open.
0..nstops beforen. Forn = 0the range is empty and the function prints nothing. - No parentheses around the condition. Rust writes
if i % 2 == 1 {and requires the braces. Parentheses are allowed, but the compiler warns that they are unnecessary. - The format string comes first.
println!("odd")prints the word, whileprintln!("{}", i)prints a value. The first argument ofprintln!is always the format string, soprintln!(i)is a compile error. - Both branches print one line. Each number produces exactly one line of output, so the output has
nlines.
Complexity
Time: O(n). The loop makes n passes with a constant amount of work in each.
Space: O(1). No data grows with n.
Edge cases and common mistakes
- Including
n. Using0..=nprints one line too many. Forn = 6it would print an extra6. - Starting at 1. The output must begin with 0, which is even and is printed as a number.
- Swapping the branches. Testing
i % 2 == 0first and putting the word in theelsegives the same output, as long as the print statements are swapped along with the test. - Printing the word for every number. Without the
else, a secondprintln!after theifwould run for odd numbers too and produce two lines. - Quotes around the number.
println!("i")prints the letteri, not its value.
Testing
n = 6prints 0, odd, 2, odd, 4, odd.n = 1prints 0.n = 2prints 0 and then odd.n = 0prints nothing.
