Cyclomatic Complexity
Cyclomatic Complexity
Complex Code
10 – 20 Medium Testability
Medium Cost and Effort
Cyclomatic complexity is calculated using the control flow representation of the program
code.
In control flow representation of the program code,
Nodes represent parts of the code having no branches.
Edges represent possible control flow transfers during program execution
There are 3 commonly used methods for calculating the cyclomatic complexity-
Method-01:
Cyclomatic Complexity = Total number of closed regions in the control flow graph + 1
Method-02:
Cyclomatic Complexity = E – N + 2
Here-
E = Total number of edges in the control flow graph
N = Total number of nodes in the control flow graph
Method-03:
Cyclomatic Complexity = P + 1
Here,
P = Total number of predicate nodes contained in the control flow graph
Note-
Problem-01:
IF A = 354
THEN IF B > C
THEN A = B
ELSE A = C
END IF
END IF
PRINT A
Solution-
We draw the following control flow graph for the given code-
Using the above control flow graph, the cyclomatic complexity may be calculated as-
Method-01:
Cyclomatic Complexity
= Total number of closed regions in the control flow graph + 1
=2+1
=3
Method-02:
Cyclomatic Complexity
=E–N+2
=8–7+2
=3
Method-03:
Cyclomatic Complexity
=P+1
=2+1
=3
Problem-02:
{ int i, j, k;
p[i] = 1;
k = p[i]; j=1;
p[j] = p[j-1];
j--;
p[j]=k;
}
Solution-
We draw the following control flow graph for the given code-
Using the above control flow graph, the cyclomatic complexity may be calculated as-
Method-01:
Cyclomatic Complexity
= Total number of closed regions in the control flow graph + 1
=3+1
=4
Method-02:
Cyclomatic Complexity
=E–N+2
= 16 – 14 + 2
=4
Method-03:
Cyclomatic Complexity
=P+1
=3+1
=4
Problem-03:
float z;
input(x, y);
if(y<0)
power = -y;
else power = y;
z=1;
while(power!=0)
{ z=z*x;
power=power-1;
} if(y<0)
z=1/z;
output(z);
end
Solution-
We draw the following control flow graph for the given code-
Using the above control flow graph, the cyclomatic complexity may be calculated as-
Method-01:
Cyclomatic Complexity
= Total number of closed regions in the control flow graph + 1
=3+1
=4
Method-02:
Cyclomatic Complexity
=E–N+2
= 16 – 14 + 2
=4
Method-03:
Cyclomatic Complexity
=P+1
=3+1
=4
Problem-04:
void main c { int a, b, c, max,
1. print f ('enter 3 integers"),
2. scan f (" %d %d %d", & a, & , & c),b
3. if (a >) b
4. if ( a > c)
5. Max = a
6. else max = c,
7. else if (b > c)
8. Max = b
9. else max = c
10. print and ( "a max = % d", max), 3
No. of independent paths
v (a) = e - n + 2
= 11 - 9 + 2
=4
No. of procedures = 1
∴∴ cyclomatic complexity
=e-n+2P
= 11 - 9 + 2
=4