Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Extra credit - Given a range from 1 to 100. Write a loop which prints out wether a number is odd or even.

can anyone tell me why my code doesn't work please?

import UIKit

for number in 1...100
    if (number % 2 == 0) {
        println("\(number) Even")
    } else if (number % 2 != 0) {
        println("\(number) Odd")
    } else {
        println(number)
}

1 Answer

You haven't wrapped the code after the for loop with curly braces.

Plus; what's all the tests? I don't think they're needed. The initial test has a binary outcome x % 2 == 0 is either true or false. There's no need for testing if x % 2 != 0; if the first test fails this is the only other outcome. So, you just need your first if testing for number % 2 == 0 printing out "Even", then an else to print out "Odd".

Steve.

My code looks like:

for number in 1...100 {  // <- you missed that curly brace
  if (number % 2 == 0){ // binary test - only two outcomes
    println("\(number) is even")
  } else {
    println("\(number) is odd")
  }
} // <- close it here

Thanks Steve, this has helped me a lot.

No problem! Glad it helped. :-)