Search⌘ K
AI Features

Example: Time Complexity of an Algorithm With Nested Loops

Understand how to analyze the time complexity of algorithms with nested loops in Java. Explore the step-by-step calculation of primitive operations and see how nested iterations affect overall performance.

A Program With Nested for Loops

Consider the following Java program:

Java
class NestedLoop {
public static void main(String[] args) {
int n = 5; // 1 step
int m = 7; // 1 step
int sum = 0; // 1 step
for (int i = 0; i < n; i++) { // n steps
for (int j = 0; j < m; j++) { // n*m steps
sum++; // n*m steps
}
}
System.out.println("Sum: " + sum); // 1 step
}
}

It is a simple piece of code that prints the number of times the ...