**Cyclomatic Complexity **

Cyclomatic complexity is a software metric used to measure the complexity of a program.

This metric measures independent paths through the program's source code. An independent path is defined as a path that has at least one edge which has not been traversed before in any other paths.

Cyclomatic complexity can be calculated with respect to functions, modules, methods or classes within a program.

**Compound Condition **

Where one or more Boolean operators such as the logical OR, AND, NAND, NOR are present is a conditional statement:

`1.`

`IF a OR b`

`2.`

`then procedure x`

`3.`

`else`

`procedure y`

`4.`

`ENDIF`

A **predicate** node will be created for each statement.

Check the following code fragment:

`01.`

`insertion_procedure (`

`int`

`a[], `

`int`

`p [], `

`int`

`N)`

`02.`

`{`

`03.`

` `

`int`

`i,j,k;`

`04.`

` `

`for`

`(i=`

`0`

`; i<=N; i++) p[i] = i;`

`05.`

` `

`for`

`(i=`

`2`

`; i<=N; i++)`

`06.`

` `

`{`

`07.`

` `

`k = p[i];`

`08.`

` `

`j = `

`1`

`;`

`09.`

` `

`while`

`(a[p[j-`

`1`

`]] > a[k]) {p[j] = p[j-`

`1`

`]; j--}`

`10.`

` `

`p[j] = k;`

`11.`

` `

`}`

`12.`

`}`

First and foremost, start numbering the statement.

`01.`

`insertion_procedure (`

`int`

`a[], `

`int`

`p [], `

`int`

`N)`

`02.`

` `

`{`

`03.`

`(`

`1`

`) Int i,j,k;`

`04.`

`(`

`2`

`) `

`for`

`((2a)i=`

`0`

`; (2b)i<=N; (2c)i++) `

`05.`

`(`

`3`

`) p[i] = i;`

`06.`

`(`

`4`

`) `

`for`

`((4a)i=`

`2`

`; (4b)i<=N; (4c)i++)`

`07.`

` `

`{`

`08.`

`(`

`5`

`) k=p[i];j=`

`1`

`;`

`09.`

`(`

`6`

`) `

`while`

`(a[p[j-`

`1`

`]] > a[k]) {`

`10.`

`(`

`7`

`) p[j] = p[j-`

`1`

`]; `

`11.`

`(`

`8`

`) j--`

`12.`

` `

`}`

`13.`

`(`

`9`

`) p[j] = k;`

`14.`

` `

`}`

Now you can clearly see which statement executes first and which executes last, etc. So drawing the CFG becomes simple:

Now, to calculate the cyclomatic complexity you use one of three methods:

- Count the number of regions on the graph: 4
- No. of predicates (red on graph) + 1 : 3 + 1 = 4
- No of edges – no. of nodes + 2: 14 – 12 + 2 = 4

That’s about it. Happy Coding :)

## {{ parent.title || parent.header.title}}

## {{ parent.tldr }}

## {{ parent.linkDescription }}

{{ parent.urlSource.name }}