# Condition in the Dependent Loops

I'm stuck with nested for loops that are dependent on the previous loop:

for (i=1; i<=n; i++)
for (j=1; j<=i; j++)
x = x+1


the part that is confusing me is j<=i. I'm trying to figure out the asymptotic running time.

• Just to be clear, I'm guessing that what you've talking about is code something like: for i=0; i<n; i++ { for j = 1; j<=i; j++ { x = x + 1 } }, and you're trying to figure out the computational complexity? – Jerry Coffin Feb 10 at 5:43
• Compare $\sum\limits_{i=1}^n n$ and $\sum\limits_{i=1}^n i$. – greybeard Feb 10 at 8:31
• In what sense are you stuck? Are you trying to understand what the code is doing? Are you trying to figure out the asymptotic running time? Try to be more verbose when asking a question. – Yuval Filmus Feb 10 at 9:00

## 1 Answer

Suppose that you start with some value in $$x$$. The inner loop increases $$x$$ by $$i$$. Therefore the outer loop increases $$x$$ by $$1+2+3+\cdots+n = n(n+1)/2$$. So overall, your code increases the value in $$x$$ by $$n(n+1)/2$$.

The running time of your code is proportional to the number of times that $$x$$ is increased, hence it is $$\Theta(n^2)$$.