Search code examples
swiftloopsfor-loopint

Extremely basic loop question telling whether number is even/odd


var currentnum: Int = 1

for currentnum in 1...100{
  if (currentnum % 2) != 0 {
    print("Odd number")
  }
  else{
    print("Even number")
  }
  currentnum += 1
}

Hello. I'm trying to "create a loop that iterates from 1 to 100 that prints out whether the current number in the iteration is even or odd." When I run the above code, I receive "error: expected expression after operator." What is wrong with my code (I'm new to programming). Thanks!


Solution

  • You don't need to declare var currentnum: Int = 1 in your code and increment through currentnum += 1. for-in loop does it for you. In Swift for-in syntax can be used to loop over both ranges of numbers, collections and even strings. All with the same syntax!

    It should be as follows,

    for currentnum in 1...100{
      if (currentnum % 2) != 0 {
        print("Odd number")
      }
      else{
        print("Even number")
      }
    }
    

    Good luck!