Why does this while loop act this way? - java

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.

Related

Can you change the value of i in a for loop (java)

If I were to make a for loop like so:
for(int i = 1; i<=25; i++){
if((i % 2) == 0){
i += 5;
}
}
Would I be able to change the value of i like this to where when i reaches 2, it adds 5 to the value so now i = 7?
Yes the value of i will be changed but it becomes 8 ,not 7.
Because when i = 1, then the condition i%2==0 doesn't satisfy and the if statement will be terminated without performing the addition. Then the value of i increment by 1.Now i=2 which satisfy the if condition. Then value of i will be i=2+5=7. Now the if statement will terminate and for the step expression i++ the value increment by 1.
So now the value of i = 8.

why does the for loop run twice only

i do not understand why the for loop runs twice, the first value to be printed should be 2 and the last value should be 16 and not 4 since 4 is still less than 10
i have done a for loop that increments the initial value by one but i have not tried to increment the initial value by multiplying it by the first value
for (int i = 2; i <10; i = i*i) {
System.out.println(i);
}
i expected it to run 4 times but it ran just two times
Your loop is equivalent to this:
int i = 2; // Initializer
while (i < 10) // Condition
{
System.out.println(i);
i = i * i; // Update part
}
Note how it will never enter the body of the loop when i is 10 or greater - so it will never print 16.
In other words, the execution looks like this:
Set i to 2.
Check: is i less than 10? Yes, so enter the body of the loop.
Print i.
Set i = i * i, so it's now 4.
Check: is i less than 10? Yes, so enter the body of the loop.
Print i.
Set i = i * i, so it's now 16.
Check: is i less than 10? No, so finish.
Finding what your code is doing is easy with a paper sheet and a pen...
first run, i = 2 -> i < 10 == true -> print 2
second run, i = 2*2 = 4 -> i < 10 == true -> print 4
third run, i = 4*4 = 16 -> i < 10 == false -> out
I try to explain how works for.
1) You initialized variable i = 2
2) Check i < 10
3) Print(i) = 2
--- NEXT ----
1) i = i*i (2*2) = 4
2) Check i < 10 = 4<10 = true
3) Print(i) = 4
--- NEXT ----
1) i = i*i (4*4) = 16
2) Check i < 10 = 16<10 = false
3) EXIT
First time i = 2, loop ran
second time i = 4, loop ran
third time i = 16, loop failed => break
Welcome to stackoverflow. For these cases you should learn to debug your code for better self understanding
You are squaring. 2,4,16 but 16 is greater than i<10 so it does not do that
Because of i = i*i
i = 2
1. i = 2*2 = 4 (4 < 10)
2. i = 4 * 2 = 8 (8 < 10)
3. i = 8 * 2 = 16 (16 > 10)

how many loops is this running? - java coding

I have been given "10 broken loops" to solve. I need to comment what was changed to make them correct.
I have
public class BrokenLoops {
//loop 5 times
public static void loop1() {
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
I know what the problem is, it will never be 10. 1 then 3 then 7 then 9 then 11 etc.
What I don't know is how many loops will be run if I type either !=9 or !=11
Would the code run as
If the code has !=11, would it run as
i = 1 "in loop"
1 = 3 "in loop"
i = 5 "in loop"
i = 7 "in loop"
i = 9 "in loop"
i = 11 "out of loop"
and so, there are 6 loops? The correct answer for 5 loops would be !=9?
Thanks in advance
This loop have condition to run when i is not equal 10. Because i starts at 1 and increases by 2 on every iteration, i will be always odd number and therefore can newer equal 10. So condition for loop will be always true. Simply put: your loop will go indefinitely.
About for statement from
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed once, as the loop begins.
The termination expression is invoked before each iteration. When it evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
More info about for statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
//edit
Correct code for 5 loops if you have to use '!=' comparison would be:
for(int i = 1; i != 11; i += 2)
// i==1 PASS
// i==3 PASS
// i==5 PASS
// i==7 PASS
// i==9 PASS
// i==11 FAILED, Loop ends here
although it's better to use
for(int i = 1; i < 10; i += 2)
//or
for(int i = 1; i < 11; i += 2)
this way, your loop will end after 5 loops and safer for many reasons
The loop as you have posted will run continuously as i will never get the value 10.
if you make the termination condition i != 9 then the loop will run for 4 times.
if you make the termination condition i != 11 then the loop will run for 5 times.
if you make the termination condition i <= 10 then the loop will run for 4 times.
to get it to run 10 times, change the for loop to this:
for (int i = 1; i <= 10; i++){
//Your code
}
EDIT:
Code:
for (int i = 1; i != 11; i += 2)
{
Console.WriteLine("In loop {0}", i);
}
Console.WriteLine("Out loop");
Console.ReadLine();
Output:
There are a few possible ways to solve your question.
Example 1
If you only need to get in the loop 5 times you can simple change your code to:
//loop 5 times
public static void loop1() {
for (int i = 0; i < 5 ; i++) {
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will print something like:
In loop 0
In loop 1
In loop 2
In loop 3
In loop 4
Out of loop
Example 2
Another option would be to change your termination value to !=11(Just don't forget, that if you increment would become i += 3 for example, this will become an infinite loop again):
public static void loop1() {
for (int i = 1; i != 11 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will terminate the loop once i will be equal to 11, so the output would be:
In loop 1
In loop 3
In loop 5
In loop 7
In loop 9
Out of loop
Example 3
You can also change termination to i < 10(or <=9 or <=10 or <11):
public static void loop1() {
for (int i = 1; i < 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
The output will be same as in Example 2.
Example 4
You can also add a check inside your loop to stop it after something evaluates to true:
public static void loop1() {
int checkInt = 0;
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
if (checkInt == 5) break;
System.out.println("In loop "+i);
checkInt++;
}
System.out.println("Out of loop");
}
So when checkInt will be equal to 5(loop was made 5 times), the loop will just stop. Output is the same as in Example 2 and Example 3
If the code has i !=11, would it run as
You just have to use i<10 to get the desired result

Trying To Understand The For Loop Completely

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

Java - do loop help explaining needed

Why does the following code execute six times? Please help me to understand how this works, as I've tried to get it into my head without success.
I thought it would first execute the code once, then increase count to 1, execute it a second time, increase count to 2, execute it a third time, increase count to 3, execute it a fourth time, increase count to 4, execute it a fifth time, increase count to 5, and then stop. Which means it will have executed the loop five times (for the first time, then for when count is 1, 2, 3, 4).
int count = 0;
do {
System.out.println("Welcome to Java!");
} while (count++ < 5);
Have you tried running this code?
int count = 0;
do {
System.out.println("Welcome to Java! " + count);
} while (count++ < 5);
output:
Welcome to Java! 0
Welcome to Java! 1
Welcome to Java! 2
Welcome to Java! 3
Welcome to Java! 4
Welcome to Java! 5
This should help you understand what is happening. Has others have said your confusion is most likely in how the post increment operator works.
To help you understand pre and post increment operators lets run another code sample
int a = 0;
int b = 0;
System.out.println("pre increment "+ ++a);
System.out.println("post increment "+ b++);
output:
pre increment 1
post increment 0
Summarizing: with post increment the expression is evaluated before the variable is incremented, with pre increment the expression is evaluated after the variable is incremented.
Its postfix operator so first evalution of whole expression then increment
Control will flow like this
0
Welcome to Java!
//condition check : 0 then 1
Welcome to Java!
//condition check : 1 then 2
Welcome to Java!
//condition check : 2 then 3
Welcome to Java!
//condition check : 3 then 4
Welcome to Java!
//condition check : 4 then 5
Welcome to Java!
//condition check : 5 then 6
That's because you're using post-increment. The while condition is first evaluated (with the count value from BEFORE the increment) and then count is incremented.
Try ++count (which first increments and then returns value).
edit:
Note that although using it in
for(int i = 0; i < n; i++) {}
is ok (it will usually get optimized, etc.),
for(int i = 0; i < n; ++i) {}
is a little bit better from the semantic point of view IMO.
It gets even more complicated in languages with operator overloading, where i++ can have different sideffects than ++i.
count++; // <-- would execute the above code 6 times
is post increment and
++count; // <-- would execute the above code 5 times
is pre increment
Consider:
while (count++ < 5) System.out.println(count); // prints 1 2 3 4 5
while (++count < 5) System.out.println(count); // prints 1 2 3 4
So your do...while executes first without a comparison (because of the do) then runs the comparison.
If it's pre-increment it could be re written like this:
int count = 0;
do {
// print
count = count + 1;
} while (count < 5)
If it's post-increment it could be re written like this:
int count = 0;
while (count < 5) {
// print statement
count = count + 1;
}

Categories