0

I didn't understood the concept of the For-In loop in swift 3 , can anyone explain to us it m thanks in advance

var total = 0
for i in 0..<4 {
total += i
}
print(total)

The result of total is 6 , Why ?

9
  • 1+2+3 = 6 ? You loop from 0 to smaller than 4, mean 0 -> 3 Commented May 18, 2017 at 9:31
  • 2
    Try putting a print statement in the loop and log the values of total and i at each iteration – that will show you what's happening. Commented May 18, 2017 at 9:31
  • what if it is 0..<5 Commented May 18, 2017 at 9:33
  • 2
    I would also recommend having a read of the range operator section of the language guide. Commented May 18, 2017 at 9:37
  • 1
    @MalikTürk No it doesn't Commented May 18, 2017 at 9:39

2 Answers 2

1

i=0 => total = 0+0 =0

i=1 => total = 0+1 = 1

i=2 => total = 1+2 = 3

i=3 => total = 3+3 =6

it's simply alogrithm ;-)

i never reach 4 because you said it STRICTLY inferior to 4 =)

(Do I answer your question?)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you , but when i change it to 0..<5 it give 11 rather than 10 :/
You need to change 0...4 if you want to execute fro 0 to 4
@Tristan I made a mistake , i assumed the value of total as 1 , then all values are executed total +1
0

Your loop will be vary from 0 to 3 i.e. 0,1,2,3 but if you want it will vary from 0 to 4 then try this -

var total = 0
for i in 0...4 {
total += i
}
print(total)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.