Find Number Combinations in Java

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops

What You’ll Learn

This page covers two classic nested-loop patterns: listing all orderings of three numbers (permutations), and listing unordered pairs or triples (combinations). You will see distinct-index checks, the j = i + 1 trick, a live preview, worked Java examples, edge cases, and complexity.

Permutations

Order matters

All 3! = 6 orderings of three values.

Combinations

Order ignored

Unordered pairs with j > i.

Distinct i, j, k

No reuse

Do not reuse the same index in one line.

n Choose r

C(n,2)

Pair loops list each 2-subset once.

Live Preview

1, 2, 3

List all orderings for three integers.

O(n²) Pairs

Nested cost

Pairs are quadratic; triples are cubic.

Introduction

Number combinations on this page means listing selections from a small array with nested loops. When order matters, you print permutations. When order does not matter, you print combinations.

Interviews love these patterns because they force you to talk about indices, duplicates, and asymptotic growth. Nested loops are enough for small sample sizes; larger inputs often use dedicated libraries later.

Why it matters?

It is the clearest way to practice nested loops while learning the difference between order-sensitive and order-free listing.

Key Highlights

Permutations

Distinct i, j, k indices.

Pairs

Use j = i + 1.

Triples

Use i < j < k.

Count

3! = 6; C(4,2) = 6.

In short: nested loops pick indices; enforce distinct indices for permutations and increasing indices for combinations.

📝 Problem & Approach

Given a small array of numbers, print either all orderings of three values or all unordered selections of size 2 or 3.

java
// [1, 2, 3] -> 6 orderings (permutations)
// [10, 20, 30, 40] -> 6 unordered pairs

Inputs & Outputs

ItemTypeDescription
arrint[]Source numbers to rearrange or pair.
Permutationstext linesOne line per ordering of three values.
Combinationstext linesOne line per unordered pair or triple.

Minimal workflow

Pseudocode
// Permutations of 3
for i in 0..2:
  for j in 0..2:
    for k in 0..2:
      if i, j, k are all distinct:
        print arr[i], arr[j], arr[k]

// Unordered pairs
for i in 0..n-2:
  for j in i+1..n-1:
    print arr[i], arr[j]

Method comparison

PatternOrder?Index rule
Permutations of 3MattersAll indices distinct
Unordered pairsIgnoredj = i + 1 .. n-1
Unordered triplesIgnoredi < j < k

⚡ Quick Reference

GoalPattern
Distinct indicesif (i != j && j != k && i != k)
Unordered pairsfor (int j = i + 1; j < n; j++)
Unordered triplesfor (int k = j + 1; k < n; k++)
Count perms of 33! = 6
Count pairsC(n, 2) = n*(n-1)/2
Library laterutility methods / custom helpers

📋 Permutation vs Combination vs Utility

Same nested-loop toolbox, different index rules and interview signals.

Permutations
distinct i,j,k

Order matters, 6 lines for [1,2,3]

Combinations
j = i + 1

Order ignored, no reverse duplicates

Utility
helper method

Production shortcut after you can explain loops

Interview tip
say order rule

State whether order matters up front

Context

When This Problem Shows Up

Reach for nested selection loops whenever you need every ordering or every unordered subset.

  1. Nested-loop drills

    Practice indices and distinctness checks.

  2. Permutation vs combination talk

    Clarify whether order changes the answer.

  3. Brute-force warm-ups

    Try all pairs before smarter algorithms.

  4. Counting practice

    Connect output line count to n! and C(n,r).

  5. Not for huge n

    Deep nested loops explode quickly.

Key benefit: one page that teaches both order-sensitive and order-free listing with the same nested-loop skill.

🔮 Live Preview

Enter three integers such as 1, 2, 3 and list all orderings.

Use commas or spaces. Duplicate values may cause repeated-looking lines.

Live result
Press “List orderings”.

Examples Gallery

Three complete Java programs: permutations of three numbers, unordered pairs, and unordered triples. Click View Output to reveal sample console results.

📚 Getting Started

Order matters: list every arrangement of three values.

Example 1 — All Orderings of Three Numbers

Order matters here, so this is permutation listing.

java
public class ThreePermutations {
    static void printThreePermutations(int[] arr) {
        System.out.println("All orderings (permutations) of the three numbers:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++) {
                    if (i != j && j != k && i != k) {
                        System.out.println(arr[i] + " " + arr[j] + " " + arr[k]);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        printThreePermutations(arr);
    }
}

How It Works

Each loop picks one position. The distinct-index guard ensures one slot is not reused in the same line. For three distinct values you always get 3! = 6 lines.

⚡ Combinations (Order Ignored)

Increasing indices keep each unordered selection once.

Example 2 — All Pairs from Four Numbers

Order does not matter in this pair listing, so we use j = i + 1.

java
public class UnorderedPairs {
    static void printUnorderedPairs(int[] arr) {
        int n = arr.length;
        System.out.println("All unordered pairs (choose 2 from " + n + "):");
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                System.out.println(arr[i] + " " + arr[j]);
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40};
        printUnorderedPairs(arr);
    }
}

How It Works

Starting the inner loop at i + 1 skips reverse duplicates like (20, 10). That is choose 2 from 4, so you get C(4, 2) = 6 pairs.

Example 3 — Unordered Triples (Choose 3)

Extend the pair idea to three nested loops with i < j < k.

java
public class UnorderedTriples {
    static void printUnorderedTriples(int[] arr) {
        int n = arr.length;
        System.out.println("All unordered triples (choose 3 from " + n + "):");
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
                    System.out.println(arr[i] + " " + arr[j] + " " + arr[k]);
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40};
        printUnorderedTriples(arr);
    }
}

How It Works

Each triple appears once because indices always increase. C(4, 3) = 4 lines, the natural extension of Example 2.

🧠 How Nested Selection Works

1

Store values

Put numbers in an array for index access.

Setup
2

Nest the loops

Each loop picks one index or position.

Loops
3

Apply the index rule

Distinct indices, or strictly increasing indices.

Filter
=

Print each selection

One line per valid tuple or pair.

🔎 Worked Walkthrough — [1, 2, 3]

Trace how distinct indices produce the six permutations.

i, j, kValuesPrinted?
0,1,21 2 3Yes
0,2,11 3 2Yes
0,0,1No (i == j)
1,0,22 1 3Yes
remaining valid triplesTotal 6 lines

Invalid index triples are skipped; only distinct i, j, k print.

Use Cases

Where listing combinations and permutations shows up beyond the interview prompt.

1. Nested Loop Practice

Learn indices and guards clearly.

Example: three nested for loops.

2. Brute-Force Pairs

Try every unordered pair first.

Example: Example 2 style.

3. Counting Checks

Verify line count equals n! or C(n,r).

Example: 6 perms, 6 pairs.

4. Teaching Order

Show why (10,20) differs from (20,10) in permutations.

Example: permutation vs combination.

5. Bridge to Factorial

Permutation counts connect to factorials.

Example: related topic.

6. Small Grids Only

Keep n small for hand-written loops.

Example: roughly 3 to 10 elements.

Pro Tip: open with “Does order matter?” That single question picks the right index rule.

Advantages

Why nested-loop listing works well for small interview problems.

  1. 1. Easy to Trace

    Dry-run indices on paper and see each line.

  2. 2. Teaches Both Ideas

    Same loops, two different meanings of order.

  3. 3. No Extra Libraries

    Works with plain Java loops and arrays.

  4. 4. Extensible

    Pairs become triples by adding one loop.

Pro Tip: lead with loops in interviews; mention utility helpers only as a production aside.

Usage Tips

Small habits that keep combination and permutation code interview-ready.

  1. 1. Ask About Order

    Decide permutation versus combination first.

  2. 2. Prefer Increasing Indices

    For combinations, j = i + 1 beats filtering later.

  3. 3. Count Expected Lines

    Check against n! or C(n,r) before finishing.

  4. 4. Watch Duplicate Values

    Distinct indices do not guarantee unique printed value tuples.

  5. 5. Keep n Small

    Mention utility methods for large production lists.

Pro Tip: if you see both (a,b) and (b,a), you probably wanted combinations, not permutations.

Common Pitfalls

Mistakes that commonly break combination and permutation listings.

  1. 1. Reusing an Index

    Printing arr[i] twice in one line.

    → Require all indices distinct for permutations.

  2. 2. Reverse Pair Duplicates

    Printing both (10,20) and (20,10).

    → Start inner loop at i + 1.

  3. 3. Confusing Terms

    Calling permutations “combinations”.

    → State whether order matters.

  4. 4. Ignoring Duplicate Values

    Expecting unique lines when input repeats.

    → Filter by value if needed.

  5. 5. Huge Nested Depth

    Hand-writing O(n^k) for large n and k.

    → Use better algorithms or helpers.

Edge Cases

Handle these before claiming the listing is complete.

Duplicates

Repeated values

Distinct indices can still print identical-looking triples.

Small n

Too few elements

For pair listing, if n < 2 there are no pairs to print.

n = 3

Exact size for perms

Example 1 assumes exactly three elements.

Triples

n < 3

Unordered triples print nothing.

Large

Large n

Output volume grows fast, O(n²) and O(n³).

Empty

Empty array

No selections, print a clear message if needed.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Order rule. Permutations count arrangements; combinations count subsets.
  • Counts. P(3,3) = 6; C(4,2) = 6; C(4,3) = 4.
  • Linked to factorial. Full permutations of n distinct items equal n!.
  • Index vs value. Distinct indices do not guarantee distinct printed values when the array has duplicates.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Reproduce 6 perms

  • Run Example 1 on [1,2,3]
  • Confirm exactly 6 lines

2. Pairs from 4

  • Reproduce Example 2
  • Confirm C(4,2) = 6

3. Triples from 4

  • Implement Example 3
  • Confirm C(4,3) = 4

4. Duplicate values

  • Try [1,1,2] in the live preview
  • Notice repeated-looking lines

Notes

  • Permutations: distinct i, j, k indices give all orderings.
  • Combinations: j > i avoids duplicate pair reversals.
  • Concept: order matters for permutations, not for combinations.
  • For many elements, prefer dedicated algorithms or helpers. Repeated values may create repeated-looking lines; filter if unique output is required.

Quick Takeaway: nest loops, then choose distinct indices for permutations or increasing indices for combinations.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Triple nested loops (fixed size 3)O(1) for fixed inputO(1)
Pairs from n elementsO(n²)O(1)
Triples from n elementsO(n³)O(1)

Cost grows with how many selections you enumerate; output size is part of the story.

Wrap Up

🎉 Conclusion

Number combinations on this page are nested-loop listings: distinct indices for permutations, increasing indices for combinations. Count expected lines with n! or C(n,r), watch duplicate values, and keep n small for hand-written loops.

Practice the three examples above, then continue to checking odd numbers.

Ask “does order matter?” then pick distinct indices or j = i + 1.

💡 Best Practices

✅ Do

  • State whether order matters
  • Use distinct indices for permutations
  • Use j = i + 1 for pairs
  • Check line count versus formula
  • Keep sample n small

❌ Don’t

  • Reuse the same index in one line
  • Print reverse pair duplicates
  • Mix up permutation and combination vocabulary
  • Ignore duplicate input values
  • Deep-nest huge n without a plan

Key Takeaways

Knowledge Unlocked

Five things to remember about number combinations

List selections with nested loops the interview-friendly way.

5
Core concepts
C 02

Combos

j = i + 1

Rule
! 03

Distinct

No reused index

Guard
# 04

Count

n! / C(n,r)

Check
O 05

Cost

O(n²) pairs

Analysis

❓ Frequently Asked Questions

This page shows two patterns: all orderings of three numbers (permutations), and all unordered pairs from four numbers (combinations).
Each loop picks one position in the triple. Distinct index checks ensure one array slot is not reused in the same line.
There are 3! = 6 permutations.
It avoids duplicates like both (10,20) and (20,10). Each unordered pair appears once.
Yes. Example 2 is choose 2 from 4. Loops list each subset explicitly.
Pair generation is O(n^2). Triple nested loops over n elements are O(n^3).
In real apps, library helpers are fine. Interviews often want you to show nested loops first.
Distinct indices can still print identical-looking lines. Filter by value if you need unique printed tuples.
Use i < j < k with three nested loops so each subset of size 3 appears once.

Did you Know? 🔊

In math, a combination ignores order, while a permutation treats different orders as different results. This page demonstrates both patterns using simple nested loops.

Continue to Odd Number

Learn how to check whether a number is odd in Java.

Odd number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful