For loop iteration increment value by 1.why? - java

Why k value is one increment when it should stop to 1 in first iteration and 3 in second iteration and so on?
public class pattern6 {
public static void main(String... args) {
int i, j, k, space = 5;
for (i = 1; i <= 5; i++) {
for (j = 0; j < space; j++)
System.out.print(" ");
space--;
for (k = i; k <= 2 * i - 1; k++)
System.out.print(k);
System.out.print("k value:" + k); // k value is incremented by 1
if (i > 1)
for (int temp = k - 2; temp >= i; temp--) {
System.out.print(temp);
}
System.out.println("");
}
}
}
Output is:
run:
1k value:2
23k value:42
345k value:643
4567k value:8654
56789k value:108765
BUILD SUCCESSFUL (total time: 0 seconds)
Why k value is 2,4,6,8 etc?

The loop stops when k is 2, 4, 6, 8 etc and it doesn't rollback the increment.
After the loop, k has the value which caused the loop to stop otherwise it should still be looping.

I don't understand your question.... I can see the output is already increased by 1 as your expectation. It is not 2,4,6,8 as you mentioned:
1k value:2
23k value:42
345k value:643
4567k value:8654
56789k value:108765
for (k = i; k <= 2 * i - 1; k++)
System.out.print(k);
System.out.print("k value:" + k); // k value is increment by 1
If you want the code print the corresponding value one by one, you can clearly state that:
for (k = i; k <= 2 * i - 1; k++){
System.out.println("temp k value:" + k); // k value is increment by 1
}
System.out.println ("final K value:"+k);

Related

Complexity Analysis that makes every element in the array equal to largest element

What is the complexity of the given code as a function of the problem size n? Show the details
of your analysis.
for (int i = 0; i < 2*n; i++)
{
if (i == n)
{
for (int j = 0; j < i; j++)
for (int k = 0; k < i; k++)
O(1)
}
else
{
for (int j = 0; j < i; j++)
O(1)
}
}
My thoughts so far:
The if statements could not always be true (could be log n)
Nested inner for loops are n^2.
Any help on how to solve it or how to proceed with it would be appreciated.
Thank you.
Without the if(i == n) {} , the number of operation is :
1 + 2 + 3 + 4 + 5 + ... + n*2
= (2n * (2n-1))/2
But at i==n , the number of operations is not i like the rest, it's i².
So the final number of operations is :
((2n * (2n-1))/2) - n + n²
The Big O notation of the above is O(n²)

The iteration variable is +1 outside the for-loop?

I have an array of size 4 and I want to check if the array contains the number 8 (which it obviously does not, the code is just for testing).
In the for-loop j goes from 0 to 3, so the final value of j in the loop is 3. However I don't follow why the value of j after the loop has been changed to 4, why is it still not 3?
public class Test {
public static void main (String[] args) {
int[] a = new int[4];
a[0] = 2;
a[1] = 3;
a[2] = 4;
a[3] = 5;
int n = a.length; // n = 4
int number = 8;
int j;
for (j = 0; j < n; j++) {
if (a[j] == number) {
System.out.println("The number is at place " + j);
break;
}
// Last value of j is 3:
System.out.println("Value of j after each iteration " + j);
}
// But here j is 4?
System.out.println("Value of j after the for-loop: " + j);
}
}
The output:
Value of j after each iteration 0
Value of j after each iteration 1
Value of j after each iteration 2
Value of j after each iteration 3
Value of j after the for-loop: 4
Yes because at the end of a for loop there is an increment to the variable. A for loop can be rewritten as:
int j = 0;
while(j < n) {
//code
j++;
}
So on the last iteration j will be incremented, it will go to the condition, and it will be false so the body of the for loop will not be entered. In order for the loop to end, j has to be more than or equal to the condition.
Think about it...
This is your for loop:
for (j = 0; j < n; j++){
//your code here
}
You start your for loop with j = 0 and every time you iterate through it, you have to check if the value is less than n ( j < n ).
To achieve that you have to increment it on every iteration.
So this is what happens for n = 4:
1st iteration:
j = 0;
0 < 4 == true;
// you execute your code
j++; //As you can see you increment before you continue to the next iteration
2nd iteration:
j = 1; // j now equals 1 because you incremented it on the previous iteration
1 < 4 == true;
// you execute your code
j++;
3rd iteration:
j = 2;
2 < 4 == true;
// you execute your code
j++;
4th iteration:
j = 3;
3 < 4 == true;
// you execute your code
j++;
5th iteration:
j = 4;
4 < 4 == false;
// loop ends
As you can see, when your code is about to start the fifth iteration, the j variable now equals 4 so it doesn't pass the j < n criteria.
However, it still incremented in the 4th iteration so you get j = 4.
This was how my teacher explained it to me when I was just starting my coding education, I hope it helps you as it helped me!
New to programming?
for(initialization; booleanExpression; updateStatement) {
; // Body
}
The steps is,
Initialization statement executes
If booleanExpression is true continue, else exit loop
Body executes
Execute updateStatements
Return to Step 2
So the end value should be 4

Formula for counting loop iteration

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

Can you help me to calculate time complexity of this algorithm?

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.

Why does my Java "for" loop immediately end?

My first loop seems to build the array correctly and when I go to print out the results in the second "for" loop it immediately terminates. I cannot see the error. Here is the code:
public class CoinFlip
{
private static int Flip()
{
return (int)(2*Math.random()); //returns 0 or 1; 0=Tails,1=Heads
}
public static void main(String args[])
{
int HEADS = 1;
int[] ConsecArray = new int[1000]; // the odds of ever having more than 1000 HEADS consecutively flipped are nil
int Sequencecounter = 0;
for (int i = 0; i < ConsecArray.length; i++)
{
if (Flip() == HEADS)
{
Sequencecounter++;
}
else // we have a TAILS
{
// Check sequence counter, if > 0, logging to do...
if (Sequencecounter > 0)
{
// Update length counters
int index = Sequencecounter - 1;
ConsecArray[index]++;
Sequencecounter = 0;
}
// consecutive tails, continue in loop
}
}
int j = ConsecArray.length;
System.out.println("Length" + " " + "NumberRunsOfHeads");
for (int k = 0; k == j; k++)
{
int index = k + 1;
String bucketName = Integer.toString(index);
String bucketValue = Integer.toString(ConsecArray[k]);
System.out.println(bucketName + " " + bucketValue);
}
}
}
The first iteration of your 2nd loop:
k is 0
j is 1000
the test k == j fails
the loop never runs
Change
for (int k = 0; k == j; k++)
into
for (int k = 0; k < j; k++)
I think you mean either k <= j or k < j, but you put k == j. This is not true during first iteration, so loop body never executes.
for (int k = 0; k == j; k++)
{
int index = k + 1;
String bucketName = Integer.toString(index);
String bucketValue = Integer.toString(ConsecArray[k]);
System.out.println(bucketName + " " + bucketValue);
}
Instead of for (int k = 0; k == j; k++) (which is equivalent to if (k == j)) you meant to write or for (int k = 0; k < j; k++), i.e. loop j times, not loop as long as k == j.
This:
for (int k = 0; k == j; k++)
Should be this:
for (int k = 0; k < j; k++)
kett_chup is right. I Think you want "k < j". You're thinking of "until" rather than "for".

Categories