Why is this for loop giving this output? - java

Why is the output of the following code: 13 15 17
I think it should be: 15 17 19
Here's the code:
package com.example.barker;
class dog {
}
public class Bark {
public static void main(String[] args) {
Bark o = new Bark();
o.go();
}
void go(){
int y =7;
for(int x = 1; x<8; x++) {
y++;
if(x>4) {
System.out.print(++y + " ");
}
}
}
}

I think the Anwer is right.
I will Explain the working of the code to get understand.
First
y=7
x=0
and after first iteration
y=8 (y++;) and x=1 (int x = 1;) (not printing because x not greater then 4)
after Second Iteration
y=9 (y++;) and x=2 (x++;) (not printing because x not greater then 4)
after Third Iteration
y=10 (y++;) and x=3 (x++;) (not printing because x not greater then 4)
after Fourth Iteration
y=11 (y++;) and x=4 (x++;) (not printing because x not greater then 4)
after Fifth Iteration
y=12 (y++;) and x=5 (x++;)
Now x is greater than 4 and going to System.out.print(++y + " ");
Here you are writing ++y ,means pre-increment
ie, increment y and printing
ie, y=13 and x=6 printing(13)
After next Iteration
y=14(y++;) and before printing the value of y doing ++y
ie,
y=15 (++y;) printing(15)
After next Iteration
y=16(y++;) and before printing the value of y doing ++y
ie,
y=17 (++y;) printing(17)
So the Output is 13 15 17
Thanks and happy coding.

Change the conditions like below, to get your desired result.
for(int x = 1; x<10; x++) {
y++;
if(x>6) {
System.out.print(++y + " ");
}
}

Let's first understand the operations happening within the for loop:
y++ will perform the +1 operation after the line of code finishes executing
++y will first perform the +1 operation and then execute the rest of the line of code
Now, let's look at the for loop:
for(int x = 1; x<8; x++) {
y++;
if(x>4) {
System.out.print(++y + " ");
}
}
For each iteration, we will look at the values for x and y:
x = 1, y = 7 (start of first iteration)
x = 1, y = 8 (end of iteration)
x = 2, y = 8 (start of first iteration)
x = 2, y = 9 (end of iteration)
x = 3, y = 9 (start of first iteration)
x = 3, y = 10 (end of iteration)
x = 4, y = 10 (start of first iteration)
x = 4, y = 11 (end of iteration)
x = 5, y = 11 (start of first iteration)
x = 5, y = 12 (y++ line)
x = 5, y = 13 (x > 4, and because of that, ++y executes)
The logic has become pretty apparent, but you can continue to debug this yourself.

Hope this helps.
Here, goes the explanation :
y=7 //At Start
When you enter in the loop:
x = 1 and y = 8
x = 2 and y = 9
x= 3 and y = 10
x = 4 and y = 11
x = 5 // which makes the if condition true
y will become 12 and when it goes into if System.out.print(++y + " ")
It will first increment then prints.
So, it will print y = 13.
Similarly, when x = 6 y will be 14 and in if it becomes 15 and so on.

Related

Not receiving correct output for the following nested for loop

I need an explanation for the following loop:
public static void main(String[] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 6;
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + " " + y);
}
The way I'm seeing it is that the 'outer' loop is running 3 times and the 'inner' loop is running 9 times. When I go through the 'inner' loop, x becomes 6, and we break out of the 'inner' loop after we get the value for y, which is 28. So now, the value of x is 6, and now I go through the 'outer' loop which runs 3 times, so 3 times 2 is equal to 6, so I subtract that from 28, and I end up with 22.
Output:
6 22
Does anyone know what I am doing wrong? I know the output should be 60 10, but I am not getting this. Thanks for your help.
I have copied and pasted your code in my pc and I get the out put
60 10
I think your are running a different file in your IDE.
What IDE do you use?

Subtraction (beginner)

public class Main {
public static void main (String[] args) {
int x = 0;
int y = 0;
while (x < 5) {
y = x - y;
System.out.print(x + y);
x = x + 1;
}
}
}
When I calculate this math myself. I get these answers:
y = 0 - 0 = 0
y = 1 - 0 = 1
y = 2 - 1 = 1
y = 3 - 1 = 2
y = 4 - 2 = 2
01122
But when I compile it. I get the answer
02356
I just don't get it. Could someone explain?
You are printing x+y not y
0+0=0 ; 1+1=2; 1+2=3; 2+3=5; 2+4=6
02356
In first iteration x=0,y=0 so x-y = 0 = y and x+y=0 so 0 will be printed.
In 2nd iteration x=1,y=0 so x-y = 1 = y and x+y=2 so 2 will be printed.
thus x and y will be updated.
In your calculation, you are not updating y
Use the debug, you will see that the iterations are correct because you are manipulating the x value after the x+y operation addition

Q: Headfirst Java for-loop exercise (Mixed Messages CH5)

I have been struggling with an exercise in the Java Headfirst book( CH5: p121 for reference). It's a loop inside another loop which adds/substracts some values from instance variables.
Input:
x = x + 3
Outputs:
x= 54 y = 6
public class MixFor5 {
public static void main(String[] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 3;
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + " " + y);
}
}
My result is when doing it by myself with a notepad is x=42 y = 8 because then both loop conditions are met. What am i doing wrong? where did I go wrong in my thoughtprocess?
these are my notes -> pastebin note
I have not tried debugging first because I want to figure this by myself first so that I don't make the same mistakes in the future.
Thanks in advance,
tvanderv
if(x == 6) will never get true. The reason behind this is,
When inner = 4
x = x + 3 executes two times i.e. means x = 6.
then, inner = 3
now first x = x + 3 (before if(x == 3) condition) will give output x = 9. So x > 6 it will not break loop.
You did this step wrong in your notes.

Tracking the final variable value in for loops when code is executed

I know that the answer is 9, but when I try to work this out on paper, I keep getting that the answer is 6. I need to know what is happening with the code runs. Especially since in the beginning, the second for loop is false because x isn't less than y.
What value is printed when the above code is executed?
int w = 0;
for (int y = 0; y < 5; y++)
{
w = y - 1;
for (int x = 1; x < y; x++)
{
w = w + x;
}
}
System.out.println(w);
The only loop that matters is the last one since the first part of the loop sets w without any care about it's previous value: y = 4.
So w = 3.
Then a loop that adds 1 2 and 3 to w.
w = 3 + 1 -> w=4
w = 4 + 2 -> w = 6
w = 6 + 3 -> w = 9

Loops in Java not adhering to the condition?

I've been scratching my head over why Java will go beyond a specified condition in some loops, while seemingly adhering to the condition in other loops. I know it's a lack of understanding on my part, but I'm confused as to when I should go over or adhere to the condition when I'm manually calculating code.
As an example, I've put in a short for loop which has an end result of 15 in iTotal, and 0 in iNumber. When I originally did the calculation on paper step by step, I ended up with the answers of 14 in iTotal, and 1 in iNumber. I assumed that the code would not go below one, as the condition was greater than zero, not equal to or greater than zero.
My original attempt -
iTotal
0
5
9
12
14
iNumber
5 4 3 2 1
int iTotal = 0;
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
In comparison, the below code snippet will at 19 with a condition of less than 20, with the last statement being value of x : 19. I calculated that correctly, but I'm not sure why the above code ignores the condition and goes to zero, while the below code adheres to the condition and stops at 19.
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
Could anyone clarify how java interprets when to go over or stop at specified conditions?
In comparison, the below code snippet will at 19 with a condition of
less than 20, with the last statement being value of x : 19. I
calculated that correctly, but I'm not sure why the above code ignores
the condition and goes to zero, while the below code adheres to the
condition and stops at 19.
What you said is incorrect. The last statement printed is 19 but the last value of x is 20. This loop that you have given does in fact execute 20 times. A for loop in Java like the one you given has 3 components an integer to use as a count, a condition to test, and how to transform the count variable. In a general form it looks like this:
for(count variable, condition, transformation){
//Code goes here
//End loop
}
This for loops executes until the condition is no longer true, which is caused by applying a transformation of some sort the count variable.
Using the for loop you gave as an example:
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
We create the count variable (int x) and set it equal to 10.
We check the count variable (int x) against the condition ( x<20 ) and evaluate the result, x < 20 == true so the code within the loop is run. At the end of the code, which I have marked "End Loop" above the transformation (x + 1) is applied to the count variable before the condition is tested again to see if the loop should proceed.
x = 11 now because x was equal to 10 but we added one as specified at the end of last loop. x < 20 == true is still true so the code within the loop will be executed again. This is continued in this way until the last number.
When x = 19 we test against the condition as we have been doing and see if x < 20 == true is still true, which it is so the code is executed. When the code execution ends, the count variable is again incremented, so x = 20.
With x = 20we once again test against x < 20. This time x < 20 == false so the code inside the loop is not executed nor is another transformation applied to the variable. At this point, when the condition becomes false the loop ends. So because we said x < 20 and not x <= 20 on the 20th loop, when x = 20, this code:
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
will not run. This means that the final output of the program would occur when x = 19 not when x=20 although if you were still able to access the count variable after the loop ends (which I believe you can do with a debugger) you would see x=20
The first loop does this:
iTotal = 0
iTotal = 5
iTotal = 9
iTotal = 12
iTotal = 14
iTotal = 15
Loop end
also as the first loops transformation is written as x-- instead of x - 1 the second loop can be rewritten as:
for(int x = 10; x < 20; x++) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
in Java the ++ operator increments by 1, it is the same as x+1.
Your first loop
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
is 5+4+3+2+1 = 15 (you must have printed iTotal before you added the first iNumber). Your second loop is similar the loop body isn't entered when the condition evaluates to false.
int x = 10;
for(; x < 20; x = x+1) {
System.out.print(x + " ");
}
System.out.println(x); // x is 20
as 10,11,12,13,14,15,16,17,18,19,20 but at twenty the loop terminates.
The condition is checked before each loop, not after. So in your first example, the logic would go:
iNumber = 5
first loop iteration
check iNumber > 0. 5 > 0, so continue the loop
add 5 to iTotal (iTotal=5 after this)
decrement iNumber
second loop iteration
check iNumber > 0. 4 > 0, so continue the loop
add 4 to iTotal (iTotal=9 after this)
decrement iNumber
...
fifth loop iteration
check iNumber > 0. 1 > 0, so continue the loop
add 1 to iTotal (iTotal=15 after this)
decrement iNumber
sixth loop iteration
check iNumber > 0. 0 > 0 is false, so break out of the loop
A similar process happens with the second loop.

Categories