Trying To Understand The For Loop Completely - java

I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates.
Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below.
public class Test {
public static void main (String[] args) {
int sum = 0;
for (int k = 1; k < 10; k += 2)
{
sum += k;
System.out.print(sum + " ");
}
}
}
The output the program puts out is 1 4 9 16 25
Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3?
It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about.
My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around.
Overall my question is, how is sum equal to 1 when k is actually equal to 3.

The sections of the for loop are run at different times.
The first section is run once at the start to initialize the variables.
The second is run each time around the loop at the START of the loop to say whether to exit or not.
The final section is run each time around the loop at the END of the loop.
All sections are optional and can just be left blank if you want.
You can also depict a for loop as a while loop:
for (A;B;C) {
D;
}
is the same as:
A;
while (B) {
D;
C;
}

Let's step through your code:
We setup an int with initial value of 0 and assign it to sum.
We setup a for loop, setting int k = 1, and we will loop while k is less than 10, and after each iteration, 2 will be added to k.
So, the first iteration, k = 1. sum currently equals 0, so sum += k is actually 0 = 0 + 1 = 1. There's the 1 you are getting.
For the second iteration, k = 3. sum currently equals 1, so sum += k is actually 1 = 1 + 3 which is 4. There's the 4 that is showing up.
Repeat this for the rest of the loop!

In the first iteration of the loop, k=1. The k+=2 is only run at the beginning of the next iteration of the loop. The loop variable update condition (the last part of the for loop - i.e. the k+=2 part) never runs on the first iteration but does run on every other one, at the start. Therefore what you have is:
Iteration 1:
k=1
sum = 0 + 1; //so sum = 1
Iteration 2:
k=1+2 // so k=3
sum = 1 + 3 // so sum = 4
Iteration 3:
k=3+2 //k=5
sum = 4 + 5 //sum=9
etc...

It goes like this:
Initialize (k = 1)
Check condition (k < 10) (stop if false)
Run the code in the loop (sum += k and print)
Increment (k += 2)
Repeat from step 2
Following this logic, you get that 1 is printed first.

The last condition, k += 2 occurs after the first iteration of the loop.
So it's
k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25

k is only incremented after the loop iteration. In general for any loop the values are updated after a loop iteration so k goes 1,3,5,7,9 and so the sum is correct.

Oh believe I had same problem. And you have to understand this quickly because when you are going to start doing bubble sort it will confuse you even more.
The thing you need to understand is that, its that it doesnt actually add +2 to 'k' until its done reading whats inside your 'for loop'
So this is how it starts, its starts with what you set 'k' for which is 1.
k = 1 is it less than 10? Yes, then do whats in the 'for loop' . Sum at first was initiated to 0. then in the first loop we add the value of k to whatever sum already has. So
sum = 0, k = 1. Therefore 0 +1 = 1. then next line ouput the value of sum with space. AND here is the IMPORTANT PART, it has now reach the end of the loop. So now it will add +2 to the value that k already has.
So k = 1 + 2 = 3. And now we start the second loop.
k=3, is less than 10? yes, ok do whats in for loop. add k to whatever value that sum already has. Sum is = 1 right ? and k is now equal to 3 right? So 3 + 1 = 4. And it display sum with a space and it has reach the end of the for loop so it add +2 to k that already has 3 in it which will equal to 5. and the loop continues.
oouff hope that helps! So remember it adds +2 at the end of the loop. Sorry if theres some typos typing from my samsung kinda annoying a bit cuz i have japanese keyboard...
Good luck!
has to

Let's break up your code. The keyword for just means loop. It will start # 1 and continue as long as k is less than 10. It will also increase by k+=2. To translate, it means k = k +2
Inside the loop sum = sum + k. It will then print the value that sum has plus a space.
k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25
and keep repeating. Let me know if you still have trouble grasping this concept

Related

Syntax and Variable Declaration in Nested Loops: How Does an Inner Declaration take Precedence?

I was following an example of how to produce a script in java that computes and prints the powers of 2 (2, 4, 8, 16...) and the script looks like this:
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i = 1; i < 10; i++) {
result = 1; //why doesn't this reset result to 1 for every iteration?
e = i;
while(e > 0) {
result *= 2;
e --;
}
System.out.println("2 to the " + i + " power is " + result);
//I would expect printing "result" here would result in 2 every time...
}
}
}
The output is:
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512
My question is that if the result variable is declared as 1 within the initial for loop but outside the inner while loop, how come its value doesn't reset to 1 every time the for loop runs? It's clear to me that the for loop begins running before the while loop takes over, because the System.out.println() command is run every time. What is it about Java's structure that allows this?
You are absolutely right about result being reset to 1 in each iteration of the for loop. It does get reset.
"But why doesn't printing result give me 2 every time" you ask.
After result is being set to 1, and before that iteration of the for loop ends, the while loop runs. How many times does the while loop runs? It depends on i. In the first iteration of the for loop, the while loop loops once, in the second iteration of the for loop, the while loop loops twice, in the third iteration of the for loop, the while loop loops three times, and so on.
At the end of each iteration of the for loop, result will contain the value of 2 to the power <however many times the while loop looped for>. So at the end of the first iteration of the for loop, result is 2 because the while loop looped only once. At the end of the second iteration, result is 4 because the while loop ran twice and so result *= 2 is ran twice.
If result isn't reset, it would have become 8 by the end of the second iteration of the for loop: it got multiplied once in the first iteration, and twice in the second iteration.
please check below inline explanations
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i = 1; i < 10; i++) {
result = 1; //why doesn't this reset result to 1 for every iteration?
// Yes , result will be 1 always here, you can print the result variable before while as below
// System.out.println("Result : " + result);
e = i;
while(e > 0) {
result *= 2;
e --;
}
System.out.println("2 to the " + i + " power is " + result);
//I would expect printing "result" here would result in 2 every time...
// here the value of result will be decided based on e, here we are multiplying result with 2 , "e" no.of times
}
}
}

Does this 'for' loop stop, and why/why not? for (int i=1; 1/i > 0; i++) { }

Does this for loop ever stop?
for(int i=1; 1/i > 0; i++) {
}
If so, when and why? I was told that it stops, but I was given no reason for that.
Yes.
First iteration: i = 1, 1/1 = 1 > 0, so it loops.
Second iteration: i = 2, 1/2 = 0 !> 0 (integer division), so it stops.
First iteration: i =1, 1/1 equals 1 so continue.
Second iteration: i = 2 , 1/2 equals 0 as it is integer division, so condition is false and it stops.
Details about integer division are documented in javadoc
Yes the for loop stops after one iteration. Dividing 1 by 2 in the second iteration will cause the for loop to stop because intergers don't record decimals meaning one divided by two will be 0 rather than .5.
1/2 is evaluated as an integer, and simply chops the decimal point. Hence 1/2 = 0.
If one of those numbers was a floating point (ex. 1.0/2 or 1/2.0), it would return the expected 0.5.
in this code
for(int i=1; 1/i > 0; i++) {
//any code here
}
in your code
set the condition the number larger than 0
the counter start from 1 (integer number)
first run for loop cheek condition 1/1 > 0 => true the code execute.
after first run the counter increment by 1 .
after that the for loop cheek condition 1/2 > 0 => false the not execute and for loop stop
why the for loop stop in 1/2 because 1 integer and 2 integer
and integer / integer must = integer 1/2 = 0 (0.5 not integer)
if you use this code the for loop many many executed .
because int/float = float
1/1.0 =1 / 1/2.0= 0.5 / 1/3.0 = 0.33333 / 1/4.0 = 0.25 ...ect
for(float i=1; 1/i > 0; i++) {
//any code here
}
this is my first time posting and I am definitely a novice so if I provide incorrect information someone please correct me :).
My understanding is that because i and 1 are both of the type integer in the line:
for(int i=1; 1/i > 0; i++)
then your program will automatically perform integer division/arithmetic which results in the modulus or remainder being dropped. Therefore during the second iteration the remainder of 0.5 will be dropped resulting in 0 and thus termination of the loop.

Round Robin Algorithm, processes dont finish executing

I'm writing a simple cpu scheduler simulator, currently im at Round Robin algorithm. At this little piece of code, my way of implementing it is this:
take the total sum of the burst time from user input for keeping track when
this block should finish. as long as the sum is greater then or equal to 0, keep executing.
now, the problem is that the sum becomes negative and the block stops executing before the processes' burst time become all 0. is there any way i can fix this?
for example, suppose in our case that our input is {9, 12, 1, 1, 4, 4},
the output for phase 1 after executing all processes with quantum 4 is:
(where first column is the original array and the second one the decremented by quantum's value)
sum: 31
phase nr: 1
9 7 not zero
12 10 not zero
1 0 check
1 0 check
4 2 not zero
4 2 not zero
phase nr: 2
7 5 not zero
10 8 not zero
0 0 check
0 0 check
2 0 check
2 0 check
at this stage sum becomes negative and stops printing other processes
this is the code ive been working so far. i dont know if this explanation is clear enough, i tried to be as clear and specific as i could.
note: all jobs has an arrival time of 0
int[] a = {9, 12, 1, 1, 4, 4};
int sum = 0;
//total sum of the a[]
for (int i = 0; i < a.length; i++)
{
sum += a[i];
}
System.out.printf("\nsum: %d\n\n", sum);
int counter = 1;
while(sum >= 0)
{
System.out.printf("\nphase nr: %d\n", counter);
for (int i = 0; i < a.length; i++)
{
//prints the original array
System.out.printf("%d ",a[i]);
int value = a[i]; //takes a value from a[] at index i
value -= 2; //decrement the value by quantum 2
a[i] = value; //put the value at the same index
if (a[i] < 0) //it checks if any element is less than 0, if yes replace it with 0
{
a[i] = 0;
}
/**
*prints the array after subtracting 2 from each element
*in the original array and checks if there is any value
*equal to 0, if yes print "check" else "not zero"
*/
System.out.printf("%d \t%s",a[i], a[i]==0?"check":"not zero");
System.out.println();
}
/**
* decrements the sum based on the quantum
* multiplied by processes
* sum = sum -(quantum * numberOfProcesses)
*/
sum = sum - (4 * 6);
counter++;
}
The problem is in calculating your sum.
sum = sum - (4 * 6);
You subtract 24 in every iteration even if processes finish earlier(like in 1 quantum of time) or are already finished.
What you should subtract from sum in every iteration is the total time spent on actual processing. So if process is done (a[i] == 0) you don't proceed, and if the a[i] < 4 you subtract that value. Only when a[i] >=4 you should subtract 4 quanta.
If you want to spend 4 quanta of time for every process regardless of its real needs and if it's done or not then you calculate your sum wrong and it's not really Round Robin.
while(sum >= 0)
{
System.out.printf("\nphase nr: %d\n", counter);
for (int i = 0; i < a.length; i++)
{
//prints the original array
System.out.printf("%d ",a[i]);
int value = a[i]; //takes a value from a[] at index i
if(a[i] == 0) { continue;} // skip process if it's done
else if(a[i]<=4) { sum -=a[i]; a[i]=0;} // if process is less than one quantum then it's done and sum is decreased by time needed
else { sum -=4; a[i] -=4} // otherwise process needs more than one quantum so it uses up all 4
/**
*prints the array after subtracting 2 from each element
*in the original array and checks if there is any value
*equal to 0, if yes print "check" else "not zero"
*/
System.out.printf("%d \t%s",a[i], a[i]==0?"check":"not zero");
System.out.println();
}
// this part was completely unnecessary so it was removed to for loop above
counter++;
}
I'm not sure too fully understand your algorithm, but the computation of the sum is not correct. You should define some function that will sum the actual values in the array a[] instead of having some wrong constant computation (you use 4 for quantum instead of 2) and ignore the fact that some a's are not decremented once they are set to 0.
You can define something like :
public static int totalBurstTime(int[] bursts) {
int total = 0;
for (int b : bursts) {
total += b;
}
return total;
}
and call it to initialise the sum before the while loop, and then at the end of each loop.
Also, you should use some constants instead of magic numbers, eg
static final int QUANTUM = 2;
and use it everywhere you need...

Why does this while loop act this way?

int i = 1;
int j = 1;
while (i < 4) {
j += i;
i++;
}
System.out.println("i = " + i);
System.out.println("j = " + j);
I have the following above and I am trying to figure out how it works. I am new to java so I do not know how to debug my code yet. The output of this program says that i = 4 and j = 7. However the condition of the while loop should only execute when i < 4. Why does it execute when i = 4? I tried changing the condition to i <= 4 and it outputs i = 5. What am I missing here?
The loop counter will be incremented for every iteration through the loop. When the counter has been incremented past 3 (when it's equal to 4) the loop will stop. The loop won't run when the counter is 4, but the counter was still incremented to 4
i = 1
is 1 less than 4? Yes, so loop.
add one to i so now i = 2.
is 2 less than 4? Yes, so loop.
add one to i so now i = 3.
is 3 less than 4? Yes, so loop.
add one to i so now i = 4.
is 4 less than 4? No, leave the loop.
Print the value of i which is 4.
You enter the loop when i=3. Inside the loop, you increment i by 1 (i++). At the end of that iteration, you check if i<4, which it is not, because i=4.

How to determine how often a statement in a nested loop is executed?

I am working through a section of a text on determining complexity of nested loops using recurrence relations. In this particular example I am trying to determine how many times the count variable will be incremented as a function of n.
This is the loop I am analyzing:
for (int i = 1; i <= n; i++) {
int j = n;
while (j > 0) {
count++;
j = j / 2;
}
}
I think I understand that the first line would equate simply to n since it only executes for each value of n but it's the rest of it that I'm having trouble with. I think the answer would be something like n(n/2) except that this example is using integer division so I'm not sure how to represent that mathematically.
I've run through the loop by hand a few times on paper so I know that the count variable should equal 1, 4, 6, 12, 15, and 18 for n values of 1-6. I just can't seem to come up with the formula... Any help would be greatly appreciated!
The loop executes for n in the range [1, n]. It divides by 2 each time for the j variable, which is set to n, so the number of time the inner loop executes is floor(l2(n)) + 1, where l2 is the binary log function. Add up all such values from 1 to n (multiply by n).
The inner j loop adds the location of the first set bit to count.
Each divide by 2 is the same as a right shift until all the bits are zero.
So, 2 would be 10 in binary, and have a value of 2 for the inner loop.
4 would be 100 in binary, and have a value of 3 for the inner loop.
The outer loop seems to just multiply the location of the first set bit by the number itself.
Here is an example with n = 13.
13 in binary is 1101, so the first set bit is at location 4.
4 * 13 = 52. 52 is the final answer.
for (int i = 1; i <= n; i++) {
This loop at the top goes through the loop n times.
int j = n;
while (j > 0) {
count++;
j = j / 2;
}
This loop here goes through the loop log(n) times, noting that it is a base 2 log since you are dividing by 2 each time.
Hence, the total number of counts is n * ceiling(log(n))

Categories