skip to Main Content

So my task is to only print even indexed characters using for-in loop.

Create a for-in loop that will loop through alphabet. Inside the loop, print every other letter by continuing to the next iteration if you are on a letter you do not wish to print. (Hint: You can use the isMultiple(of:) method on Int to only print even indexed characters).

Here’s my code:

let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

for letter in alphabet {
    if letter == "F" { // letter I wish not to print
        continue
    }

    // How do I need to use isMultiple(of: ) method?

    print(letter)
}

3

Answers


  1. Chosen as BEST ANSWER

    I found out, that we need to put 'print' statement inside 'if' statement, because it will print even indexes (what task says).

    let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
    for (index, letter) in alphabet.enumerated() {
        if letter == "F" {
            continue
        }
        if index.isMultiple(of: 2) {
            print(letter)
        }
    }
    

    But if we put 'continue' inside if statement, we will skip even indexes. So the odd ones will be printed. Am I right?


  2. Here’s how you can do it.

    let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
    for (index, letter) in alphabets.enumerated() {
        if index.isMultiple(of: 2) {
            continue
        }
        print(letter)
    }
    
    Login or Signup to reply.
  3. The swifty way is enumerated()– to get indexed characters – in conjunction with a where clause.

    The where clause skips the current iteration if the condition is false.

    let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for (index, letter) in alphabet.enumerated() where index.isMultiple(of: 2) {
       print(letter)
    } 
    

    This prints "A C E …"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search