Tuesday, February 23, 2016

Control Structure in Swift

We usually used the common control structure in our programming. This post will cover 3 basic common structure in Swift; if else, for loop and while loop

if else
Eg: Create a program that checks if the user enter the correct password for a particular user.

var name = "Ange"
var pw = "password"

if name == "Ange" && pw == "password" {
    print("Welcome " + name + ", you have entered the correct               password")
    }

else if name != "Ange" && pw != "password" {
        print("You have entered the wrong username and wrong                 password")
    }

    else if pw != "password" {
            print("You have entered the wrong password")
        }

        else {
            print(("You have entered the wrong username")
            }

if else statement



for loop
Eg1: Print even number from 1 to 10

for var i = 2; i <= 10; i = i + 2 {
    print(i)
    print("\n")
}
for loop

Eg2: Create an array and divide all the elements in array by 2. Print the result.

var myArray = [2, 4, 8]

for [index, value] in enumerate(myArray} {
    myArray[index] = value / 2
}
print(myArray)
for loop to access elements in an array



while loop

Eg: Create an array with 7 elements and subtract 2 from each of them.

var myArray = [2, 4, 8]
var i = 0

while i < myArray.count {
    myArray[i] = (myArray[i] - 2)
    print(myArray)
    print("\n")
}

while loop

No comments:

Post a Comment