---
description: This tutorial covers the basics of McCabe&#039;s Cyclomatic Complexity, Flow Graph Notation, Properties, Uses, How to Calculate McCabe&#039;s Complexity, and more.
title: Cyclomatic Complexity in Software Testing with Example
image: https://www.guru99.com/images/cyclomatic-complexity-in-software-testing.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Cyclomatic Complexity is a software metric developed by Thomas McCabe in 1976 that counts the independent paths through a program. It is calculated from a control flow graph and gives the number of test cases required for full branch coverage.

* 📐 **Two Formulas:** V(G) = E – N + 2 from the graph, or V(G) = P + 1 from the count of decision points.
* 🧮 **Direct Meaning:** The value equals the maximum number of independent paths, and therefore the test cases needed.
* 🗺️ **Graph Basis:** Nodes represent processing steps and edges represent the flow of control between them.
* 🟢 **1 to 10:** Structured, well-written code with high testability and low maintenance cost.
* 🟠 **21 to 40:** Very complex code with low testability, where refactoring usually costs less than testing.
* 🛠️ **Tooling:** SonarQube, Visual Studio Code Metrics, Radon, and Lizard compute it automatically.

[ Read More ](javascript:void%280%29;) 

![Cyclomatic Complexity in Software Testing](https://www.guru99.com/images/cyclomatic-complexity-in-software-testing.png)

## What is McCabe’s Cyclomatic Complexity?

**Cyclomatic Complexity in Software Testing** is a testing metric used for measuring the complexity of a software program. It is a quantitative measure of independent paths in the source code of a software program. Cyclomatic complexity can be calculated by using control flow graphs or with respect to functions, modules, methods or classes within a software program.

Independent path is defined as a path that has at least one edge which has not been traversed before in any other paths.

This metric was developed by Thomas J. McCabe in 1976 and it is based on a control flow representation of the program. Control flow depicts a program as a graph which consists of Nodes and Edges.

In the graph, Nodes represent processing tasks while edges represent control flow between the nodes.

[](https://images/1.jpg)

## Flow Graph Notation for a Program

Flow Graph notation for a program defines several nodes connected through the edges. Below are Flow diagrams for statements like if-else, While, until and normal sequence of flow.

[](https://images/2%281%29.png)

## How to Calculate Cyclomatic Complexity

**Mathematical representation:**

Mathematically, it is set of independent paths through the graph diagram. The Code complexity of the program can be defined using the formula –

V(G) = E - N + 2

**Where,**

E – Number of edges

N – Number of Nodes

V (G) = P + 1

Where P = Number of predicate nodes (node that contains condition)

**Example –**

i = 0;
n=4; //N-Number of nodes present in the graph

while (i<n-1) do
j = i + 1;

while (j<n) do

if A[i]<A[j] then
swap(A[i], A[j]);

end do;
j=j+1;

end do;

Flow graph for this program will be

[](https://images/3%281%29.png)

**Computing mathematically,**

* V(G) = 9 – 7 + 2 = 4
* V(G) = 3 + 1 = 4 (Condition nodes are 1,2 and 3 nodes)

**Basis set**, the four independent execution paths:

* 1, 7
* 1, 2, 6, 1, 7
* 1, 2, 3, 4, 5, 2, 6, 1, 7
* 1, 2, 3, 5, 2, 6, 1, 7

## Properties of Cyclomatic Complexity

Following are the properties of Cyclomatic complexity:

1. V (G) is the maximum number of independent paths in the graph
2. V (G) >=1
3. G will have one path if V (G) = 1
4. A commonly used guideline is to keep V(G) at 10 or below for a single module

## How This Metric is Useful for Software Testing

Basis Path testing is one of White box technique and it guarantees to execute at least one statement during testing. It checks each linearly independent path through the program, which means the **number of test cases needed equals the cyclomatic complexity of the program**. 

This metric is useful because of properties of Cyclomatic complexity (M) –

1. M can be number of test cases to achieve branch coverage (Upper Bound)
2. M can be number of paths through the graphs. (Lower Bound)

**Consider this example –**

If (Condition 1)
Statement 1

Else
Statement 2

If (Condition 2)
Statement 3

Else
Statement 4

Cyclomatic Complexity for this program will be 8-7+2=3.

As complexity has calculated as 3, three test cases are necessary to the complete path coverage for the above example.

### Steps to be followed

The following steps should be followed for computing Cyclomatic complexity and test cases design.

**Step 1** – Construction of graph with nodes and edges from the code

**Step 2** – Identification of independent paths

**Step 3** – Cyclomatic Complexity Calculation

**Step 4** – Design of Test Cases

Once the basic set is formed, [TEST CASES](https://www.guru99.com/test-case.html) should be written to execute all the paths.

### RELATED ARTICLES

* [Fuzz Testing (Fuzzing) Tutorial ](https://www.guru99.com/fuzz-testing.html "Fuzz Testing (Fuzzing) Tutorial")
* [Do Testers Have to Write Code? Skills & Career Guide ](https://www.guru99.com/testers-write-code.html "Do Testers Have to Write Code? Skills & Career Guide")
* [Mainframe Testing – Complete Tutorial ](https://www.guru99.com/mainframe-testing.html "Mainframe Testing – Complete Tutorial")
* [6 BEST Software Testing Companies (2026) ](https://www.guru99.com/software-testing-company.html "6 BEST Software Testing Companies (2026)")

## More on V (G)

Cyclomatic complexity can be calculated manually if the program is small. Automated tools need to be used if the program is very complex as this involves more flow graphs. Based on complexity number, team can conclude on the actions that need to be taken for measure.

The following table gives an overview of the complexity number and the corresponding meaning of v (G):

| Complexity Number | Meaning                                                                   |
| ----------------- | ------------------------------------------------------------------------- |
| 1 to 10           | Structured and well-written code High testability Cost and effort is less |
| 11 to 20          | Complex code Medium testability Cost and effort is medium                 |
| 21 to 40          | Very complex code Low testability Cost and effort are high                |
| \>40              | Not at all testable Very high cost and effort                             |

## Tools for Calculating Cyclomatic Complexity

Many tools are available for determining the complexity of the application. Some complexity calculation tools are used for specific technologies. Complexity can be found by the number of decision points in a program. The decision points are if, for, for-each, while, do, catch, case statements in a source code.

**Examples of tools are**

* [OCLint](https://github.com/oclint/oclint) – Static code analyzer for C and Related Languages
* [SonarQube](https://www.sonarsource.com/products/sonarqube/) – Reports cyclomatic and cognitive complexity across more than 25 languages
* Visual Studio Code Metrics – Built-in cyclomatic complexity analysis for .NET assemblies
* Radon and Lizard – Command-line complexity analysers for Python and for multi-language projects respectively
* [GMetrics](https://github.com/dx42/gmetrics) – Find metrics in[ Java ](https://www.guru99.com/java-tutorial.html)related applications

## Uses of Cyclomatic Complexity

Cyclomatic Complexity can prove to be very helpful in

* Helps developers and testers to determine independent path executions
* Developers can assure that all the paths have been tested at least once
* Helps us to focus more on the uncovered paths
* Improve code coverage in [Software Engineering](https://www.guru99.com/what-is-software-engineering.html)
* Evaluate the risk associated with the application or program
* Using these metrics early in the cycle reduces more risk of the program

## How to Reduce Cyclomatic Complexity

A high complexity number is a signal, not a verdict. Four refactorings account for most of the reduction achievable in practice.

* **Extract method.** Moving a branch into its own function splits the complexity between two modules. The total across the system is unchanged, but each unit becomes independently testable.
* **Replace a conditional chain with a lookup.** A long if-else-if ladder testing the same variable becomes a map or a switch, which collapses many decision points into one.
* **Use guard clauses.** Returning early on invalid input removes the nesting that a single large if-else block creates, without changing behaviour.
* **Replace conditionals with polymorphism.** Where a conditional switches on a type, moving each branch into its own class removes the decision entirely.

Before, with V(G) = 4:

if (user != null) {
    if (user.isActive()) {
        if (user.hasRole("admin")) {
            return grantAccess();
        }
    }
}
return denyAccess();

After, with the same behaviour and the nesting removed:

if (user == null) return denyAccess();
if (!user.isActive()) return denyAccess();
if (!user.hasRole("admin")) return denyAccess();
return grantAccess();

**A caution about the metric.** Cyclomatic complexity counts decisions, not difficulty. A switch statement with twenty simple cases scores 21 yet is easy to read, while a deeply nested block scoring 8 may be far harder to understand. Use the number to find candidates for review, not as a target to be gamed.

## FAQs

📐 What is a good cyclomatic complexity value?

Ten or below per module is the common guideline. Between 11 and 20 the code is complex but manageable. Above 20 testability falls sharply, and above 40 the module is generally considered untestable as written.

🧮 Which formula should you use, E – N + 2 or P + 1?

Both give the same result. P + 1 is faster for hand calculation because you only count decision points. E – N + 2 is what tools use, since they already build the control flow graph.

🔄 Does a switch statement with many cases mean bad code?

Not necessarily. Cyclomatic complexity counts decisions rather than difficulty, so a flat switch with twenty simple cases scores highly while remaining easy to read. Treat the number as a prompt for review.

🤖 How do AI code review tools use cyclomatic complexity?

They combine it with change frequency and defect history to rank which modules carry the most risk, directing review and test effort to the code most likely to fail.

🧠 Can AI suggest refactorings to lower complexity?

Yes. AI assistants propose guard clauses, extracted methods, and lookup tables that reduce the count. Verify behaviour with the existing test suite, because a refactoring that changes logic defeats the purpose.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/cyclomatic-complexity-in-software-testing.png","url":"https://www.guru99.com/images/cyclomatic-complexity-in-software-testing.png","width":"700","height":"250","caption":"Cyclomatic Complexity in Software Testing","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/cyclomatic-complexity.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/softwaretesting","name":"Software Testing"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/cyclomatic-complexity.html","name":"Cyclomatic Complexity in Software Testing with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/cyclomatic-complexity.html#webpage","url":"https://www.guru99.com/cyclomatic-complexity.html","name":"Cyclomatic Complexity in Software Testing with Example","dateModified":"2026-07-28T19:20:55+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/cyclomatic-complexity-in-software-testing.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/cyclomatic-complexity.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/thomas","name":"Thomas Hamilton","description":"I am Thomas Hamilton, a seasoned professional in software testing, specializing in crafting comprehensive guides to help you master your software testing skills.","url":"https://www.guru99.com/author/thomas","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/thomas-hamilton-author-v2-120x120.png","url":"https://www.guru99.com/images/thomas-hamilton-author-v2-120x120.png","caption":"Thomas Hamilton","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Software Testing","headline":"Cyclomatic Complexity in Software Testing with Example","description":"This tutorial covers the basics of McCabe&#039;s Cyclomatic Complexity, Flow Graph Notation, Properties, Uses, How to Calculate McCabe&#039;s Complexity, and more.","keywords":"testing","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/thomas","name":"Thomas Hamilton"},"dateModified":"2026-07-28T19:20:55+05:30","image":{"@id":"https://www.guru99.com/images/cyclomatic-complexity-in-software-testing.png"},"copyrightYear":"2026","name":"Cyclomatic Complexity in Software Testing with Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is a good cyclomatic complexity value?","acceptedAnswer":{"@type":"Answer","text":"Ten or below per module is the common guideline. Between 11 and 20 the code is complex but manageable. Above 20 testability falls sharply, and above 40 the module is generally considered untestable as written."}},{"@type":"Question","name":"Which formula should you use, E - N + 2 or P + 1?","acceptedAnswer":{"@type":"Answer","text":"Both give the same result. P + 1 is faster for hand calculation because you only count decision points. E - N + 2 is what tools use, since they already build the control flow graph."}},{"@type":"Question","name":"Does a switch statement with many cases mean bad code?","acceptedAnswer":{"@type":"Answer","text":"Not necessarily. Cyclomatic complexity counts decisions rather than difficulty, so a flat switch with twenty simple cases scores highly while remaining easy to read. Treat the number as a prompt for review."}},{"@type":"Question","name":"How do AI code review tools use cyclomatic complexity?","acceptedAnswer":{"@type":"Answer","text":"They combine it with change frequency and defect history to rank which modules carry the most risk, directing review and test effort to the code most likely to fail."}},{"@type":"Question","name":"Can AI suggest refactorings to lower complexity?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI assistants propose guard clauses, extracted methods, and lookup tables that reduce the count. Verify behaviour with the existing test suite, because a refactoring that changes logic defeats the purpose."}}]}],"@id":"https://www.guru99.com/cyclomatic-complexity.html#schema-1153720","isPartOf":{"@id":"https://www.guru99.com/cyclomatic-complexity.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/cyclomatic-complexity.html#webpage"}}]}
```
