The Wayback Machine - https://web.archive.org/web/20240930194704/https://www.geeksforgeeks.org/cyclomatic-complexity/
Open In App

Cyclomatic Complexity

Last Updated : 05 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Cyclomatic complexity, developed by Thomas McCabe, is a metric that measures the complexity of a program by counting its decision points. It measures the number of unique paths through the code, indicating how complex the logic is. Lower complexity suggests simpler, more manageable code, reducing the chances of errors and making it easier to maintain and modify. Essentially, it helps assess the code’s readability and risk associated with changes.

What is Cyclomatic Complexity?

The cyclomatic complexity of a code section is the quantitative measure of the number of linearly independent paths in it. It is a software metric used to indicate the complexity of a program. It is computed using the control flow graph of the program. The nodes in the graph indicate the smallest group of commands of a program, and a directed edge in it connects the two nodes i.e. if the second command might immediately follow the first command.

For example, if the source code contains no control flow statement then its cyclomatic complexity will be 1, and the source code contains a single path in it. Similarly, if the source code contains one if condition then cyclomatic complexity will be 2 because there will be two paths one for true and the other for false. 

Formula for Calculating Cyclomatic Complexity

Mathematically, for a structured program, the directed graph inside the control flow is the edge joining two basic blocks of the program as control may pass from first to second. 
So, cyclomatic complexity M would be defined as, 

M = E – N + 2P

where

E = the number of edges in the control flow graph 
N = the number of nodes in the control flow graph 
P = the number of connected components 

In case, when exit point is directly connected back to the entry point. Here, the graph is strongly connected, and cyclometric complexity is defined as

M = E – N + P

where

E = the number of edges in the control flow graph 
N = the number of nodes in the control flow graph 
P = the number of connected components 

In the case of a single method, P is equal to 1. So, for a single subroutine, the formula can be defined as

M = E – N + 2

where

E = the number of edges in the control flow graph 
N = the number of nodes in the control flow graph 
P = the number of connected components 

How to Calculate Cyclomatic Complexity?

Steps that should be followed in calculating cyclomatic complexity and test cases design are:  

Construction of graph with nodes and edges from code.

  • Identification of independent paths.
  • Cyclomatic Complexity Calculation
  • Design of Test Cases

Let a section of code as such: 

A = 10
IF B > C THEN
A = B
ELSE
A = C
ENDIF
Print A
Print B
Print C

Control Flow Graph of the above code:

Cyclomatic Complexity

Cyclomatic Complexity

The cyclomatic complexity calculated for the above code will be from the control flow graph.

The graph shows seven shapes(nodes), and seven lines(edges), hence cyclomatic complexity is 7-7+2 = 2. 

Use of Cyclomatic Complexity

  • Determining the independent path executions thus proven to be very helpful for Developers and Testers.
  • It can make sure that every path has been tested at least once.
  • Thus help to focus more on uncovered paths.
  • Code coverage can be improved.
  • Risks associated with the program can be evaluated.
  • These metrics being used earlier in the program help in reducing the risks.

Advantages of Cyclomatic Complexity

  • It can be used as a quality metric, given the relative complexity of various designs.
  • It is able to compute faster than Halstead’s metrics.
  • It is used to measure the minimum effort and best areas of concentration for testing.
  • It is able to guide the testing process.
  • It is easy to apply.

Disadvantages of Cyclomatic Complexity

  • It is the measure of the program’s control complexity and not the data complexity.
  • In this, nested conditional structures are harder to understand than non-nested structures.
  • In the case of simple comparisons and decision structures, it may give a misleading figure.

Important Questions on Cyclomatic Complexity

1. Consider the following program module.

int module1 (int x, int y) {
while (x!=y){
if(x>y)
x=x-y,
else y=y-x;
}
return x;
}

What is the Cyclomatic Complexity of the above module? [GATE CS 2004]

(A) 1

(B) 2

(C) 3

(D) 4

Answer: Correct answer is (C).

2. With respect to software testing, consider a flow graph G with one connected component. Let E be the number of edges, N be the number of nodes, and P be the number of predicate nodes of G. Consider the following four expressions:

i. E-N+P
ii. E-N+2
iii. P+2
iv. P+1

The cyclomatic complexity of G is given by [GATE CS 2006]

(A) 1 or 3

(B) 2 or 3

(C) 2 or 4

(D) 1 or 4

Solution: Correct Answer is (C).

3. Consider the following statements about the cyclomatic complexity of the control flow graph of a program module. Which of these are TRUE? [ GATE-CS-2009 ]

I. The cyclomatic complexity of a module is equal to the maximum number of 
linearly independent circuits in the graph.
II. The cyclomatic complexity of a module is the number of decisions in the
module plus one,where a decision is effectively any conditional statement
in the module.
III.The cyclomatic complexity can also be used as a number of linearly
independent paths that should be tested during path coverage testing.

(A) I and II

(B) II and III

(C) I and III

(D) I, II and III

Solution: Correct Answer is (B).

4. Consider the following C program segment.

C
while (first <= last)
{
   if (array [middle] < search)
      first = middle +1;
   else if (array [middle] == search)
      found = True;
   else last = middle – 1;
   middle = (first + last)/2;
}
if (first < last) not Present = True;

The cyclomatic complexity of the program segment is __________. [ GATE-CS-2015 (Set 1) ]

(A) 3

(B) 4

(C) 5

(D) 6

Solution: Correct Answer is (C).

Conclusion

Cyclomatic complexity provides a clear measure of a program’s complexity based on its decision-making structure. By counting independent paths, it helps assess code readability and identify areas prone to errors. While it aids in test case design and code improvement, it’s crucial to remember its limitations, especially in interpreting nested structures and focusing solely on control complexity.

FAQs on Cyclomatic Complexity

1. What is Cyclometric Complexity?

Answer:

Cyclometric Complexity is basically a software metric that is used to determine the complexity of a program.

Answer:

High Cyclometric Complexity can lead to difficulties in code and also increases the risk of errors in code.

3. Is Cyclomatic Complexity a good or a bad thing?

Answer:

Cyclomatic Complexity is good if they are in fewer numbers and are bad if they are in more number.



Previous Article
Next Article

Similar Reads

Time Complexity and Space Complexity
Generally, there is always more than one way to solve a problem in computer science with different algorithms. Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more optimal. The method must be: Independent of the machine and its configuration, on which the algorithm is running on.Shows a direc
14 min read
What does 'Space Complexity' mean?
Space Complexity: The term Space Complexity is misused for Auxiliary Space at many places. Following are the correct definitions of Auxiliary Space and Space Complexity. Auxiliary Space is the extra space or temporary space used by an algorithm. The space Complexity of an algorithm is the total space taken by the algorithm with respect to the input
2 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Comparison of an Array and Hash table in terms of Storage structure and Access time complexity
Arrays and Hash Tables are two of the most widely used data structures in computer science, both serving as efficient solutions for storing and accessing data in Java. They have different storage structures and time complexities, making them suitable for different use cases. In this article, we will explore the differences between arrays and hash t
3 min read
Time Complexity Analysis | Tower Of Hanoi (Recursion)
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk ca
2 min read
Queries of nCr%p in O(1) time complexity
Given Q queries and P where P is a prime number, each query has two numbers N and R and the task is to calculate nCr mod p. Constraints: N <= 106 R <= 106 p is a prime number Examples: Input: Q = 2 p = 1000000007 1st query: N = 15, R = 4 2nd query: N = 20, R = 3 Output: 1st query: 1365 2nd query: 1140 15!/(4!*(15-4)!)%1000000007 = 1365 20!/(2
9 min read
Python Code for time Complexity plot of Heap Sort
Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort here, call it for different sized random lists, meas
3 min read
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Pre-requisite: Sieve of Eratosthenes What is Sieve of Eratosthenes algorithm? In order to analyze it, let's take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime and mark it as composite. This process continues unt
3 min read
Complexity analysis of various operations of Binary Min Heap
A Min Heap is a Complete Binary Tree in which the children nodes have a higher value (lesser priority) than the parent nodes, i.e., any path from the root to the leaf nodes, has an ascending order of elements. In the case of a binary tree, the root is considered to be at height 0, its children nodes are considered to be at height 1, and so on. Each
3 min read
Complexity Metrics
The productivity, if measured only in terms of lines of code per unit of time, can vary a lot depending on the complexity of the system to be developed. A programmer will produce a lesser amount of code for highly complex system programs, as compared to a simple application program. Similarly, complexity has a great impact on the cost of maintainin
7 min read
Time Complexity of Euclidean Algorithm
In this article, we will discuss the time complexity of the Euclidean Algorithm which is O(log(min(a, b)) and it is achieved. Euclid's Algorithm: It is an efficient method for finding the GCD(Greatest Common Divisor) of two integers. The time complexity of this algorithm is O(log(min(a, b)). Recursively it can be expressed as: gcd(a, b) = gcd(b, a%
4 min read
Constant & Linear Space Complexity in Algorithms
Being a programmer, you might have solved a lot of programming challenges. In programming space and time complexity matters a lot when we need to execute a program. Our algorithm should be efficient, and it should take less time. Whenever you're writing a solution to a program, some memory is required to complete, and it is important for our progra
5 min read
Miscellaneous Problems of Time Complexity
Prerequisite : Asymptotic Notations Time Complexity :Time complexity is the time needed by an algorithm expressed as a function of the size of a problem. It can also be defined as the amount of computer time it needs to run a program to completion. When we solve a problem of time complexity then this definition help the most - "It is the number of
15+ min read
Computational Complexity v/s Chomsky Hierarchy
1. Computational complexity :Computational complexity, a measure of the number of computing resources(time and space) that a particular algorithm consumes when it runs. The time complexity of a Turing machine is given by the function T(n), where T(n) = Maximum number of moves made by the TM to process a string of length n. The space complexity of t
4 min read
Logarithmic vs Double Logarithmic Time Complexity
Time complexity is the computational complexity that describes the amount of time it takes to run an algorithm.” Now, we know that there can be multiple ways we can solve any particular problem. But, knowing how we can solve the problem in the most efficient way is important in real-life applications. To find the efficiency of any algorithm or prob
3 min read
Can Run Time Complexity of a comparison-based sorting algorithm be less than N logN?
Sorting algorithms are the means to sort a given set of data in an order according to the requirement of the user. They are primarily used to sort data in an increasing or decreasing manner. There are two types of sorting algorithms: Comparison-based sorting algorithmsNon-comparison-based sorting algorithms Comparison-based sorting algorithms: The
3 min read
Step Count Method for Time Complexity Analysis
What is Time Complexity? Time Complexity is the amount of time taken by the algorithm to run. It measures the time taken to execute each statement of code in an algorithm. Time Complexity can be calculated by using Two types of methods. They are: Step Count MethodAsymptotic Notation. Here, we will discuss the Step Count Method. What is Step Count M
4 min read
Time and Space complexity analysis of Selection Sort
The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already sorted. (where n is the number of integers in an
2 min read
Time and Space Complexity Analysis of Tree Traversal Algorithms
Let us discuss the Time and Space complexity of different Tree Traversal techniques, such as Inorder Traversal, Preorder Traversal, Postorder Traversal, etc. Time Complexity of Tree Traversal AlgorithmsLet us see different corner cases: Complexity function T(n) — for all problems where tree traversal is involved — can be defined as: T(n) = T(k) + T
2 min read
Time and Space Complexity analysis of Stack operations
What is Stack?Stack is a linear data structure that follows a particular order in which the elements are inserted and deleted. A stack follows the principle of last in first out(LIFO) which means that the last element inserted into the stack should be removed first. Consider an example of plates stacked over one another in the canteen. The plate wh
15+ min read
P, NP, CoNP, NP hard and NP complete | Complexity Classes
In computer science, there exist some problems whose solutions are not yet found, the problems are divided into classes known as Complexity Classes. In complexity theory, a Complexity Class is a set of problems with related complexity. These classes help scientists to group problems based on how much time and space they require to solve problems an
5 min read
Time and Space complexity of 1-D and 2-D Array Operations
The time and space complexity of one-dimensional and two-dimensional array operations can vary depending on the specific operation. Here, we'll discuss common array operations and provide insights into their time and space complexities for one-dimensional and two-dimensional arrays. One-Dimensional Array Operations: Accessing an Element by Index:Ti
3 min read
Knowing the complexity in competitive programming
Prerequisite: Time Complexity Analysis Generally, while doing competitive programming problems on various sites, the most difficult task faced is writing the code under desired complexity otherwise the program will get a TLE (Time Limit Exceeded). A naive solution is almost never accepted. So how to know, what complexity is acceptable?The answer to
6 min read
What is the difference between Auxiliary space and Space Complexity?
Space complexity and Auxiliary space are two of the most often confused and interchangeably used terms when talking about the space complexity of a certain algorithm: Auxiliary Space: The extra space that is taken by an algorithm temporarily to finish its workSpace Complexity: Space complexity is the total space taken by the algorithm with respect
4 min read
Time Complexity of building a heap
Consider the following algorithm for building a Heap of an input array A. BUILD-HEAP(A) heapsize := size(A); for i := floor(heapsize/2) downto 1 do HEAPIFY(A, i); end for END A quick look over the above algorithm suggests that the running time is [Tex]O(n * lg(n)) [/Tex] since each call to Heapify costs [Tex]O(lg(n)) [/Tex]and Build-Heap makes [Tex
2 min read
Time complexity of insertion sort when there are O(n) inversions?
What is an inversion? Given an array arr[], a pair arr[i] and arr[j] forms an inversion if arr[i] j. For example, the array {1, 3, 2, 5} has one inversion (3, 2) and array {5, 4, 3} has inversions (5, 4), (5, 3) and (4, 3). We have discussed a merge sort based algorithm to count inversions What is the time complexity of Insertion Sort when there ar
1 min read
Can QuickSort be implemented in O(nLogn) worst case time complexity?
The worst-case time complexity of a typical implementation of QuickSort is O(n2). The worst case occurs when the picked pivot is always an extreme (smallest or largest) element. This happens when the input array is sorted or reverses sorted and either the first or last element is picked as a pivot. Although randomized QuickSort works well even when
15+ min read
An interesting time complexity question
What is the time complexity of following function fun()? int fun(int n) { for (int i = 1; i <= n; i++) { for (int j = 1; j < n; j += i) { // Some O(1) task } } } For i = 1, the inner loop is executed n times. For i = 2, the inner loop is executed approximately n/2 times. For i = 3, the inner loop is executed approximately n/3 times. For i = 4
2 min read
Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..
What is the time complexity of below code? C/C++ Code #include <iostream> using namespace std; void fun(int n) { int j = 1, i = 0; while (i < n) { // Some O(1) task i = i + j; j++; } } C/C++ Code void fun(int n) { int j = 1, i = 0; while (i < n) { // Some O(1) task i = i + j; j++; } } Java Code // Method with a parameter 'n' static void
2 min read
Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
For such cases, time complexity of the loop is O(log(log(n))).The following cases analyse different aspects of the problem. Case 1 : for (int i = 2; i <=n; i = pow(i, k)) { // some O(1) expressions or statements } In this case, i takes values 2, 2k, (2k)k = 2k2, (2k2)k = 2k3, ..., 2klogk(log(n)). The last term must be less than or equal to n, an
1 min read