r/javahelp • u/MrTemotion • May 12 '19
Solved Why does x equal 40 after the code executes?
int x = 10;
for (int y = 5; y < 20; y +=5)
x += y;
1
3
u/shagieIsMe Extreme Brewer May 12 '19
Lets make this actual code... and put some print statements in.
package net.shagie.misc;
public class Twenty {
public static void main(String[] args) {
int x = 10;
System.out.println("x = " + x);
for (int y = 5; y < 20; y +=5) {
x += y;
System.out.println();
System.out.println("y = " + y);
System.out.println("x = " + x);
}
}
}and the output:
x = 10
y = 5
x = 15
y = 10
x = 25
y = 15
x = 40And, well... there's your answer. Just take the code and compile it.
You can also easily do this with an IDE (without needing to print things out) by putting a breakpoint in and stepping through the code. https://i.imgur.com/E6RdzWz.png
Learning how to debug is essential. From How To Be A Programmer
Debugging is the cornerstone of being a programmer. The first meaning of the verb "debug" is to remove errors, but the meaning that really matters is to see into the execution of a program by examining it. A programmer that cannot debug effectively is blind.
2
6
u/codingtorinado May 12 '19
10+5+10+15