+ 4

Why isn't the code working ?

I was trying a write a code, which will print the sum of every number from 1 to 100, but I am not getting the output of the value of a variable.. The code is - public class Program { public static void main(String[] args) { int X = 1; int Y = 100; while ( X <= Y ) { int K = X + 1; int B = K + X; ++X; } System.out.println("The sum of every number from 1 to 100 is"); System.out.println(B); } }

20th Jul 2020, 7:52 AM
Shouvik
Shouvik - avatar
9 Answers
+ 3
Ok, I just searched in google. At first there were no useful results but after changing the keywords I got what I needed. The link - https://www.quora.com/In-Java-how-do-I-use-a-variable-that-has-been-declared-in-a-while-loop-Inside-the-while-I-have-accepted-the-input-of-the-user-and-in-the-same-main-method-I-am-trying-to-use-the-input-but-it-says-Variable-not-declared-How-can-I-get-rid-of-this They have their value but it only stays inside the braces of the whole loop, outside of the whole loop braces, there is no K variable and therefore no value.
20th Jul 2020, 1:14 PM
Shouvik
Shouvik - avatar
+ 2
Why isn't it working, where did I foget a semicolon ?
20th Jul 2020, 8:04 AM
Shouvik
Shouvik - avatar
+ 2
I understand how your code is working but in spite of removing the semicolon my code is still not working, can you do some correction in my code and make it work ?
20th Jul 2020, 8:09 AM
Shouvik
Shouvik - avatar
+ 1
So does this mean we can't declare variables inside while loop ?
20th Jul 2020, 8:17 AM
Shouvik
Shouvik - avatar
+ 1
Ok.......well, this will take me quite some time to understand but ok...so this means when a new K variable is created, it takes the value of K + X, but as it is recreated in the while loop and K has no value, so this will not show any results.....I hope its right..
20th Jul 2020, 8:49 AM
Shouvik
Shouvik - avatar
+ 1
Okk, then in my code lets take X = 1 Y = 3 And everything the same K = X + 1 = 1+1 = 2 B = K + X = 2+1 = 3 ++X = (X = X+1) = 2 Then K and B loses its value but X has the value of 2 K = X + 1 = 2+1 = 3 B = K + X = 3+2 = 5 ++X = (X = X+1) = 3 So here the while loop should stop cause X becomes equal to Y and K and B still has value of 3 and 5, but for some reason the programme terminates after creating a new K and B, is this the function of JAVA ?
20th Jul 2020, 9:15 AM
Shouvik
Shouvik - avatar
+ 1
PRANAV RODGE I have already understood my mistakes but what will be the difference between using ++X and X++ ?
21st Jul 2020, 8:24 AM
Shouvik
Shouvik - avatar
0
You have not used a good method of swapping Instead of 2 variable you can use only one that is temp . And instead of ++X use X++
21st Jul 2020, 7:39 AM
PRANAV RODGE
0
Use System.out.println(B); inside the while loop insted of using it outside of the loop because you are calculating each value so when you use it inside the loop it will give you the correct answer
22nd Jul 2020, 6:59 AM
Kamal Chilwal
Kamal Chilwal - avatar