Sunday, 26 February 2017

Loop : for and while




// for in : loop to iterate over a sequence, such as ranges of numbers
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}

//for in : If you don’t need each value from a sequence, you can ignore the values by using an underscore in place of a variable name. 
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")


//Use a for-in loop with an array to iterate over its items. 
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}

// (key, value) tuple’s members as explicitly named constants for use within the body of the for-in loop.
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}

// while statement
var i  = 0;
while(i < 10)
{
    print(i);
    i = i+1;
}

// repeat while statement
var j  = 0;
repeat
{
    print(j);
    j = j+1;
}while(j < 10)

No comments:

Post a Comment