Here's how you can loop through an array of numbers from 0 to 10 and add every second number:
main.swift99 chars9 lines
In the above code, we first initialize a variable sum
to 0. Then we loop through the range 0 to 10 (excluding 10) using a for
loop. Inside the loop, we use an if
statement to check if the current number is even or odd. If the number is even (i.e., every second number), we use the continue
keyword to skip rest of the loop body and move on to the next iteration. If the number is odd, we add it to sum
.
At the end, we print the final value of sum
.
gistlibby LogSnag