-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLec9_Control_Structures.R
More file actions
74 lines (63 loc) · 1.05 KB
/
Lec9_Control_Structures.R
File metadata and controls
74 lines (63 loc) · 1.05 KB
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
71
72
73
74
# if construct
# if (condition) {
# statements
# }
# if else construct
# if (condition) {
# statements
# } else {
# statements
# }
# if else if construct
# if (condition) {
# statements
# } else if (condition) {
# statements
# } else {
# statements
# }
# Example
x <- 10
if (x > 0) {
print("Positive")
} else if (x < 0) {
print("Negative")
} else {
print("Zero")
}
# Sequence function
# seq(from, to, by, length)
# Creates equi-spaced points between from and to
print(seq(1, 10, 2)) # 1 3 5 7 9
print(seq(1, 10, length = 5)) # 1.00 3.25 5.5 7.75 10.00
print(seq(1, 10, by = 4)) # 1 5 9
# for loop construct
# for (variable in sequence) {
# statements
# }
n <- 5
sum <- 0
print("i sum")
for (i in seq(1, n)) { # OR for (i in 1:n)
sum <- sum + i
print(c(i, sum))
if (i == 2) {
next # like continue in C
}
if (i == 3) {
break
}
}
# while loop construct
# while (condition) {
# statements
# }
n <- 5
sum <- 0
i <- 1
print("i sum")
while (i <= n) {
sum <- sum + i
print(c(i, sum))
i <- i + 1
}