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
Chris Freeman
1,077 PointsExtra 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
Steve Hunter
57,712 PointsYou 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.
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsMy code looks like:
Chris Freeman
1,077 PointsChris Freeman
1,077 PointsThanks Steve, this has helped me a lot.
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsNo problem! Glad it helped. :-)