Back to the 2023 paper

Module 3: Software Design & Metrics

20237m

What is cyclomatic complexity? Write a C program to calculate GCD of two numbers and calculate the cyclomatic complexity of the program.

Worked SolutionAI Assisted

Solution

Cyclomatic Complexity

V(G)=E−N+2PV(G)=E-N+2P or V(G)=P+1V(G)=P+1 where PP = predicate nodes. Measures independent paths.

C Program - GCD

#include <stdio.h>
int gcd(int a,int b){
  while(b!=0){          // P1
    int t=b;
    b=a%b;
    a=t;
  }
  return a;
}
int main(){
  int x,y; scanf("%d%d",&x,&y);
  if(x<=0 || y<=0){     // P2 (with || = 2 predicates)
    printf("Invalid");
    return 0;
  }
  printf("GCD=%d",gcd(x,y));
  return 0;
}

Complexity Calculation

For gcd function alone:

  • Predicate: while(b!=0) → 1
  • V(G)=1+1=2V(G)=1+1=2

For main with validation:

  • Predicates: b!=0 (1), x<=0 (2), y<=0 (3) → P=3P=3
  • V(G)=3+1=4V(G)=3+1=4
  • Via graph: E=11,N=9,P=1E=11, N=9, P=1 → V=11−9+2=4V=11-9+2=4

Paths: Need 4 test cases (e.g., (48,18), (0,5), (5,0), (18,48)).

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.