Back to the 2021 paper

Module 3: Software Design & Metrics

20217m

What is cyclomatic complexity? How is it computed? Calculate cyclomatic complexity for the program to find the smallest of three numbers.

Worked SolutionAI Assisted

Solution

Cyclomatic Complexity

Definition: V(G)=E−N+2PV(G) = E - N + 2P (McCabe) = number of linearly independent paths. Also V(G)=textdecisionnodes+1V(G) = \\text{decision nodes} + 1.

Computation: Count if, for, while, case, &&, ||.

Example: Smallest of 3 numbers

int smallest(int a,int b,int c){
  int m = a;
  if(b < m) m = b;  // P1
  if(c < m) m = c;  // P2
  return m;
}

Control Flow Graph: 2 predicates → V(G)=2+1=3V(G) = 2 + 1 = 3

  • Via formula: E=7,N=6,P=1E=7, N=6, P=1 → V=7−6+2=3V=7-6+2=3

Paths:

  1. a is smallest (both false)
  2. b is smallest (first true)
  3. c is smallest (second true)

So 3 independent paths → needs 3 test cases.

Similar questions

Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.