Lesson 7.3 · Answer it
Handshake count
4 marksYou mark it yourself against the marking points
At a meeting of n people, everyone shakes hands once with everyone else. Each new person shakes hands with everyone already counted. This function counts the handshakes, one turn of the inner loop for each.
def handshakes(n):
count = 0
for i in range(n):
for j in range(i):
count = count + 1
return count
public static int handshakes(int n) {
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
count = count + 1;
}
}
return count;
}
(a) State the value the function returns when n is 6. [1]
(b) State the Big O complexity of the function. [1]
(c) The inner loop does not run n times on every turn of the outer loop. Explain why the function still has the complexity you gave in (b). [2]
[4]