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(Control flow)

Given a range of numbers from 1 to 100. Write a loop which prints out whether a number is a odd or even.

I write a loop but it kinda works wrong. It either prints all even or odd numbers depends which one i wrote first, that's how my code looks like:

for i in 1...100 {
    if i % 2 != 0   {
        println("\(i) is even")
    } else if i % 2 == 0 {
        ("\(i) is odd")
    }

}

please help me to complete this task. Appreciation in advanced

4 Answers

My Xcode is updating at the moment so I can't try this out - I'll edit my code in a minute as it'll be wrong first time !

Your loop looks right - your conditional isn't.

if i % 2 == 0, i is even, else it is odd. You don't need a second test - there are only two outcomes. And your tests are the wrong way round. i % 2 being zero means i is even.

for i in 1...100 {
  if i % 2 == 0 {
    println("\(i) is even")
  } else {
    println("\(i) is odd") 
  }
}

That's my first crack at it without the IDE!

Steve.

What you wrote is going to print either only even or odd numbers depending which statement satisfies first, in your case it's even numbers - so it is exactly the same as my code. What I want is to print both even and odd numbers just showing which one is even and which is odd

1 - is odd 2 - is even 3 - is odd 4 - is even 5 - odd ....... and so on

It works fine.

When i is 1, the test i % 2 == 0 fails so the else clause fires, stating "1 is odd".

When i iterates to 2, the conditional test i % 2 == 0 is true, so the first part of the if fires; "i is even".

It works exactly how you want. Try it!

Steve.

Hell yes )) you right!! I did not pay attention. Thanks for help!

No problem! :-)

Steve, I got some problems with My SQL, can you please check it? I asked here but get no respond yet.

https://teamtreehouse.com/community/mysql-has-different-views-than-shown-here