-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathloops.swift
70 lines (50 loc) · 1.01 KB
/
loops.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// loops
// for
var vegetables = [ "carrots", "beetroots", "potatoes" ]
for vegetable in vegetables {
print("I like \(vegetable)")
}
// range in for loop
for i in 1...5 {
print(i) // 1 2 3 4 5 - 5 is included
}
for i in 1..<5 {
print(i) // 1 2 3 4
}
// counter variable or loop variable
for _ in 1...7 { // _ is used when you don't care about the loop variable
print("I love coding")
}
// break
var names = [ "anupeddi", "ragpeddi", "abhipatthi" ]
for name in names{
if name == "abhipatthi"{
print("found \(name)")
break
}
}
// output : found abhipatthi
// continue
var names = [ "anupeddi", "ragpeddi", "abhipatthi" ]
for name in names{
if name.hasSuffix("peddi") == false {
continue
}
print(name)
}
// output
// anupeddi
// ragpeddi
// while
// while loop will run until the condition becomes false
var num = 7
while num > 0 {
print(num)
num -= 1
}
// using random method
var dice = 0
while dice != 6 {
dice = Int.random(in: 1...6)
print(dice)
}