So recently I am having trouble understanding nested for loops. For example, one question asks: The following nested loop structure will execute the inner most statement (x++) how many times?
for (int j = 0; j < 100; j++)
{
for (int k = 100; k > 0; k--)
{
x++;
}
}
Can you keep it in simple terms, as I am fairly new to programming? Thanks!
For every inner loop, the for loop will execute x++ 100 times. You will also run the inner for loop 100 times. So in total you will run x++ 100 x 100 = 10000 times.
For each j, the k loop executes a 100 times hence incrementing x by 100. See illustration below:
for j=0; k=100, k=99, k=98 .... k=2, k=1; x is now 100
for j=1; k=100, k=99, k=98 .... k=2, k=1; x is now 200
.............................................
.............................................
for j=98; k=100, k=99, k=98 .... k=2, k=1; x is now 9900
for j=99; k=100, k=99, k=98 .... k=2, k=1; x is now 10000
The result would have been the same, had the code been modified as:
for(int j = 0; j < 100; j++) {
for(int k = 0; k < 100; k++) // NOTE: reversal of k here.
{
x++;
}
}
The inner k loop is just being executed in reverse order (from 100 to 0) just to confuse the newbies.
You just have to understand how many times each loop executes.
Note that first loop runs 100 times. So, everything inside it will repeat 100 times. The inner loop also runs 100 times. So x++ will execute 100 * 100 = 10000 times.
for (int j = 0; j < 100; j++) // 100 times
{
for (int k = 100; k > 0; k--) // 100 * 100 times
{
x++; // 100 * 100 times
}
}
System.out.println("x = " + x); // This should print 10000 (assuming that x is zero initially)
for(int j = 0; j < 100; j++) //j -> 0~99 =>total=100
{
for(int k = 100; k > 0; k--) //k -> 100~1 =>total=1oo
{
x++;
}
}
System.out.println(x); //should print 10000 bcz of 100*100
Related
count++;
count++;
count++;
for (int i = 0; i < n; i++)
{
for(int j = 0; j < i*i; j++)
{
for (int k = 0; k < j; k++)
{
count++;
sum++;
}
}
}
count++;
return count;
}
Trying to get the Big O of this coding. Struggling to understand how the loops interact. When I run it, I get n = 25 count = 898960. I've tried O(n)^5+9 all the way to O(n)^5/n
All other examples of this problem don't deal with I is used in the second loop (I*I) and j is used in the third loop
Almost always the best way to compute complexities of kinda loops should be done by making use of sigma notation.
P.S. I don't write necessary +1s in the formulas since it is not important for Big-O notation and doesn't affect max power which is 5.
It looks like it is O(n^5).
for (int i = 0; i < n; i++) // 0 to n -> O(n)
for(int j = 0; j < i*i; j++) // 0 to n * n -> O(n^2) repeated n times -> O(n^3)
for (int k = 0; k < j; k++) // 0 to n * n -> O (n^2) repeated O(n^3) times -> O(n^5)
In the best case scenario, three nested loops would give you O(n^3), but as you have the second loop repeat (n^2) times, that will square its complexity and of the third loop as well. So in a simple mathematical notation that will be: (n) * (n * n) * (n * n) = n^5.
The sum is -9 but i'm having trouble figuring out why. I don't understand how the j-- in the for loop will increment. It should be incremented after the body is executed, right? But doesn't the initialization of the for loop make j-- pointless? So I assume that on the 2nd iteration j becomes 2 because of i++. Could someone help look at this the right way?
public static void whatsTheSum(){
int sum = 1;
int i = 1;
while(i < 5){
for(int j = i; j > 0; j--)
sum += (j - i);
i++;
}
System.out.println(sum);
}
I don't understand how the j-- in the for loop will increment. It should be incremented after the body is executed, right?
It's updated, then, yes. (The update is a decrement, not an increment.) But yes, it happens after each time the loop body is run.
But doesn't the initialization of the for loop make j-- pointless?
No. The initialization has j start with the value from i, and then count down while j is > 0 (without changing i).
So I assume that on the 2nd iteration j becomes 2 because of i++.
The second iteration of the while loop, yes. j will start out at 2 and then the for loop will run twice (for j = 2 and j = 1).
Just for complete clarity, here's how a for loop works:
for (initialization; test; update) {
body;
}
That's executed in this order:
Do initialization
Evaluate test, if false leave the loop
Do body
Do update
Jump to Step 2
To what I understand the requirement stated in the question above to increment j to iterate from 0 to i, you would require something like -
while(i < 5){
for(int j = 0; j < i; j++) {
sum += (j - i);
}
i++;
}
also j++ can be replaced as j=j+1 , j += 1 they would have eht esame effect and the order is very nicely explained by #T.J's answer.
So if you have nested loops its always good to write down each and every iteration:
i = 1, sum = 1
1. while (i < 5) = true so
1.1 for(int j = 1; j > 0; j--) j=1
sum += (1-1)
i=2 sum =1
2. while (i < 5) = true so
2.1 for(int j = 2; j > 0; j--)
sum += (2-2) --> sum = 1
2.2 for(int j = 1; j > 0; j--)
sum += (1-2) --> sum = 0
i=3 sum =0
3. while (i < 5) = true so
3.1 for(int j = 3; j > 0; j--)
sum += (3-3) --> sum = 0
3.2 for(int j = 2; j > 0; j--)
sum += (2-3) --> sum = -1
3.3 for(int j = 1; j > 0; j--)
sum += (1-3) --> sum = -3
And so on
I have spent so much time trying to find the formula for this code, but still nothing .. I know the running time but the question really is, what if n = 100 for example, how many line of output will this code print? Is there any specific formula to get the count? The code I've done:
int i, j, k;
for (i = 1; i <= n; i++) {
for (j = i + 1; j <= n; j++) {
for (k = j + 1; k <= n; k++) {
System.out.println(i + " " + j + " " + k);
}
}
}
I have a feeling that you are requiring a formula to get number of iteration the nested loops will.
for( i = 1; i <= n; i++ )
for ( j = i+1; j <= n; j++ )
for( k = j+1; k <= n; k++ )
For those loops, the number of iterations will be:
(n*(n-1)*(n-2))/6, where n > 2.
Generic formula for above kind nested loops:
(n*(n-1)* ... *(n-r+1)) / r!, where n > r-1.
Here, r = number of nested loops
For example: when n = 20 and r = 3, number of iterations will be = (20*19*18) / 3! = 1140
Strictly, i < j < k. What's more, 1 ≤ i < j < k ≤ n.
Or in other words, the number of lines printed is the number of different unordered sets of 3 different numbers from a total set of n numbers. You can continue from here.
Hint: combination
for(int i =0; i <= 1; i++)
{
for(int j =0; j <= i; j++)
{
System.out.print(i);
}
}
Output: 011
I just want to know how this happened.
You have two loops:
for(int i =0; i <= 1; i++) //external loop
for(int j =0; j <= i; j++) //internal loop
System.out.print(i);
The external loop has 2 iteration since it starts in i = 0 and ends in i = 1 when i is incremented to i = 2 you exit the for loop.
The internal loop has i + 1 iterations.
When i = 0 the internal loop iterates once. That`s when you get the 0.
When i = 1 the internal loop iterates twice (j = 0 and j = 1). That`s when you get 11
public static void complexityexample(int n) {
int count = 0;
int k = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
count++;
}
k *= 2;
for (int t = 0; t < n; t++) {
count++;
}
System.out.println(count);
}
}
Can anyone write me the answer?
for example , I know that nuber of operations in the for loop is 2N+2,
and number of operations in count++; is N
but what for the other parts.
Time complexity is O(2n). The bottle neck is :
for(int j = 0; j < k; j++){
count++;
}
Since k increases exponentially every iteration of i.
In the i'th iteration, k = 2i-1. This means iterating all values from j to k is O(k) = O(2i).
Now, sum it all up for all iterations:
20 + 21 + 22 + ... + 2n-1 = 2n - 1
Where last equality comes from sum of geometric series
Note that the next inner loop:
for (int t = 0; t < n; t++) {
is not influencing the time complexity (in terms of asymptotic notation), since it adds O(n) time for each iteration of i, and this gets quickly suppressed by the exponential behavior of the first inner loop.
If you want to count the value of count at the end, it is the summation of the first inner loop, which as said is (2n)-1, and the second inner loop, which is sum{n | for each i} = n2.
(2^n)+(n*n)
as them main loop is
for (int i = 0; i < n; i++) {
2^n from :
for (int j = 0; j < k; j++) {
count++;
}
and n*n from:
for (int t = 0; t < n; t++) {
count++;
}
1st row ) 1 operation.
2st row ) 2 operations.
3rd row ) 1+n+1+n = 2N+2.
4 ) 2N+2
5)N
7) N
9)2N+2
10)N
13)1
Is this right.
And after all math calculations the final result is : 14N^2 + 22N + 11 - operations.
A precise methodology using Sigma notation would be:
Empirically verified:
When n = 10, number of overall iterations is 1123.
When n = 25, number of overall iterations is 33555056.
When n = 50, it took for ever to execute (I had to change variables type from int to long).
Indeed, this non polynomial algorithm is expensive.