DSA Factory
Free lessonsProgramming basics · Stage 8 · Loops inside loops · Step 1

A loop inside a loop

Make every item meet every other item, with a loop inside a loop. About 10 minutes.

Everyone shakes hands

At a party, everyone shakes hands with everyone else, once. How do you count the handshakes? Take the first person, and they shake hands with each of the others. Then take the second person, and so on.

In code, that's a loop inside a loop. The outer loop picks a person. The inner loop goes through the people they shake hands with. For every single pass of the outer loop, the inner loop runs all the way through from start to finish.

The inner loop runs in full: for every pass of the outer loop.

Start the inner loop later

If the inner loop also started from the first person, you would count a person shaking hands with themselves, and every handshake twice, once from each side. That's wrong.

The fix: the inner loop starts just after the outer person. Person 1 meets 2, 3, 4, and so on. Person 2 meets 3, 4, and so on, because they already met 1. Each pair then appears exactly once, with the smaller number first.

Inner loop starts after the outer, so each pair is counted once.
In code
count = 0
for a in range(1, n + 1):
    for b in range(a + 1, n + 1):
        if a + b == total:
            count = count + 1
Pairs from 1 to 5 that add up to 6
1
0
2
1
3
2
4
3
5
4
ab
a
1
b
2
count
0

The outer loop picks a = 1. The inner loop starts after it, at b = 2. 1 plus 2 is 3, not 6.

Move 1 of 5
Quick check

Four people meet, and everyone shakes hands with everyone else, once. How many handshakes is that?

  1. A6
  2. B12
  3. C4
Show the answer

6. Person 1 shakes 3 hands, person 2 shakes 2 more, and person 3 shakes 1 more. 3 + 2 + 1 = 6.

Your problem

Pairs that add up

Count the pairs of whole numbers a and b with 1 ≤ a < b ≤ n and a + b equal to total. Each pair is counted once.

Example
n = 5, total = 6 → 2

0 ≤ n ≤ 1,000 · 0 ≤ total ≤ 2,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding