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 trialAngelo Pappano
5,964 PointsNested For Loops
I think you should touch on nested for loops - really useful. Here's a useful one I tried to find all of the prime numbers - it worked really well to watch the loop count climb as it went through each of the iterations. I added the "break" to cut the number of loops down dramatically.
for i in 2...100 {
var prime = true
for j in 2..<i {
if i % j == 0 {
prime = false
//break
}
}
if prime == true {
println("\(i) is a prime number")
}
}
and here's a prime number checker:
//Prime Number Checker
var input = 453111
var prime = true
for j in 2..<input {
if input % j == 0 {
prime = false
println("\(input) is not prime. It is divisible by \(j)")
break
}
}
if prime == true {
println("\(input) is, in fact, a prime number")
}
A great add on to let the learner know how to use "break" and also understand iterations a little better.
1 Answer
Emmanuel Ouzan
4,107 PointsNice thinking Angelo!
This is a bit complicated for such a simple thing to do ;)
You are right that in bigger programs when we are asked to check a lot more elements/parameters so a loop like you just wrote will be useful and time saving.
But I think that for now its enough that students will write the same code as Amit Writes. :)
Emmanuel.