Why do I get this output? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
why do i get this output ? I expect the output to be 10,9,8...
But it is 11,12,13....
class tester {
static int i = 0;
public static void main(String args[]) {
recursive();
System.out.println("after recursive");
}
public static void recursive() {
while(i++<10) {
recursive();
System.out.println(i);
}
}
}

The simple logic is as follows:
Since your incremental is a posfix increment, the original value is evaluated first, before increment.
Logic:
while (i++ < 10) { recursive();}
i is initially 0, so, 0 < 10 (true), increment by 1. Now, call recursive().
This loops (1) until i = 10. When i = 10 is evaluated, the while expression is false, so it leaves the loop.
Remember, we have already called recursive() 10 times already, so it now needs to print i, 10 times, (since the JVM pushed recursive() function 10 times in the stack). Each times it pops the function, it goes back to the System.out.println(i) statement, knowing that i was incremented in each call, hence why you see values:
11
12
13
14
15
16
17
18
19
20
after recursive
That's basically recursion in a nutshell. :-)

It makes recursive calls until i=10. i is incremented to 11. Then it stops and you start popping back up the stack, printing i. That's why it starts with 11. Remember it is going to check the while loop condition on the way back up, which increments i again each time. That's why it goes to 12, 13,...

It's because your i variable is declared outside of your recursive variable, and you are incrementing and recursing before your display it. Don't forget that i++ < 10 will get to evaluate i++, which will increment the value of i, even if the result of i++ < 10 is false.
If you manually write down the sequence of i++ that's a result of your code's execution, and also write down when the value of i is displayed, it should all become clear.

The control only reaches System.out.println when the recursive calls have stopped, and by that time the guard of the loop is false, which means i > 10 after the last comparison (i == 10 in this last comparison, but it gets post-incremented).

You are printing out the value of i. Nowhere in your code there's any statement that could decrease the value of i. Therefore you shouldn't be expecting to see decreasing values being printed out.
That aside, it is generally a bad idea to have recursion keep state in a global variable (here, i) as this tends to make it extremely hard to reason about what's happening in the code.

Related

My Java Runtime can not execute my for-loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
I've been trying to get this loop working for almost two hours and I don't know what I'm doing wrong.
This is what my code looks like:
for(int i=0; i==10; i++) {
System.out.println(i)
}
I tried it with ++i, i-- and --i but nothing seems to work.
TL;DR: Try to replace the condition i == 10 with i<10.
i is being initialized to 0, and before the first iteration gets executed, the condition i == 10 is checked, which returns false. Thus resulting in the loop never being executed.
If you want to execute the for() loop a few number of times (in your case, maybe 10?), you need to put a condition that holds true until you increment i that number of times.
Putting i<10 in place of i==10 would result in evaluating a condition that holds true for all i (0, 1, 2, 3, ...) until 10.
If you want to loop 10 times use:
for(i = 0; i < 10; i++){
System.out.println(i)
}
If you want to loop until i equals 10 use:
for(i = 0; i <= 10; i++){
System.out.println(i)
}

Does breaking an outer loop allow the inner loop finish all it's execution? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Might be a simple question but, having two nested loops, if I execute a break over the outer one, will the inner one break immediately too; Or will it let it finish its execution, then break the outer one right after?
For example:
outer: for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
if (j == 5) break outer;
System.out.println(j);
}
System.out.println("test");
}
Would this piece of code print numbers from 0 to 5 before it breaks the outer loop or would it print numbers from 0 to 10 instead?
Will the System.out.println("test"); execute too?
It will print numbers from 0 to 4.
5 not included, as the print is not executed when the condition is met (j==5). If you wish to include it, change the condition to (j>5).
Regarding your second question, no, "test" would never be printed. The labeled break finishes the outer loop (with every statement inside, including the inner loop) and ends your program's execution, by just printing:
0
1
2
3
4
Edit: tested and confirmed, above's the resultant output.

Java: How to write a condition for operators? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
enter image description here
I need some help for an if condition. I know how the basic one works: if x == 1, return something. But how am I supposed to do it, when I need to define certain cases for different operators. Like if the operators is + then the result denoted the sum.
So basically I need to translate the condition in the link into base cases for a recrsive method. We learned that we always use if for basecases. I know how to that with smaller or bigger then, but with operators I don't know.
FYI: if() is not a loop while() is. if() statement works as true or false, if the statement is true then execute a certain code other wise some other code.
For example:
if(1==1){// yourcode } // Always as true
// or
String hello="hi there";
if(hello.contains("hi there")){ // Your code which if the statement happen to be true }
else { // Not true}
int x=3, s=1, i=2;
if(x==(s+i)){ // Your code which if the statement happen to be true }
else { // Not true}
also you can find a lot of tutorials online to help you better understand all the operators!
Are you trying to state if its positive or negative? If so you would do the following...
if(x >= 0){ //this operator is saying if x is greater than or equal to 0
// you can remove the equal sign to have it just greater or
// switch it to less than.
//if positive
}else{
//all other numbers, which would just be negative numbers
}

What is difference between below Code 1 & Code 2? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Code 1
String ccMailAddresses="abc#co.in,xyz#co.in";
String ccMailAddressArray[]=ccMailAddresses.split(",");
for (int index = 0; index < ccMailAddressArray.length; index++) {
System.out.println(ccMailAddressArray[index]);
}
Code 2
String ccMailAddresses="abc#co.in,xy";
for (String ccMailAddress : ccMailAddresses.split(",")){
System.out.println(ccMailAddress );
}
Which is best practice ? Is any performance hit in any one of them ?
Obviously, the second piece of code is shorter and working on a higher level of abstraction - as it is using a for-each loop; instead of that counting-for loop.
In that sense: code2 requires less efforts for the reader to grasp what is going on. So, from that perspective, it is definitely "better" than code1.
Performance wise, there shouldn't be any different between the two.
The code does nearly the same thing. The if-statement in Code1 is useless. In my opinion this is alway true.
The difference is betweeen those two line:
for (int index = 0; index < ccMailAddressArray.length; index++)
Here your code will be executed until your index is bigger than the lenght of your array.
for (String ccMailAddress : ccMailAddresses.split(","))
The code in this loop is executed for every element in your array.
But keep in mind the result is the same!
hope that helps!
No difference between both code:
code1 is traditional for loop , and code2 is for each loop introduced for java collection to iterate.
Code 1
String ccMailAddresses="abc#co.in,xyz#co.in";
String ccMailAddressArray[]=ccMailAddresses.split(",");
if(ccMailAddressArray!=null){
for (int index = 0; index < ccMailAddressArray.length; index++) {
System.out.println(ccMailAddressArray[index]);
}
}
In this example you make an unnecessary check against ccMailAddressArray because split() will never return null. The for loop here provides you an index. This can be useful sometimes e.g. if you have a color array that has a color stored for each element. Then you could use color[index] to select the color for each element and draw it somewhere. Please now, that this is a bit more complex than just iterating over all items. So you use this version whenever you need the index.
Code 2
String ccMailAddresses="abc#co.in,xy";
for (String ccMailAddress : ccMailAddresses.split(",")){
System.out.println(ccMailAddress );
}
In this example you do essentially the same. The for-each loop you're using here does the same for you. The only difference is that you don't have the index here. It's just a bit shorter and simpler which makes it also easier to read.
So: Use for-each (Code 2) whenever you can because it is a bit simpler to understand what you are dong. If you use the index based for loop (Code 1) I assume you want to do something with index which also implies that some more complicated things may be involved.
Thanks for an answer stackoverflowgigs.
My question is solved now!. As one of my senior gave me the review comment about code 2 is performance hit by repeatedly calling ccMailAddresses.split(",") in for each loop.

How does increments the integer in (all) loops work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
how does increment the integer in (all) loops work ?
Like in the first time it initialize the integer then it checks the condition then increments the value and after that it does what i told it to do or it initialize the integer then it checks the condition and it does what i told it to do then increment the value ?
In a for loop,
for (a;b;c){
// code d
}
1) It runs statement a first.
2) Then checks statement b.
3a) If b fails it exits the loop.
3b) If it passes, it executes d ONCE. If at any point in d does it exit (eg. break), it will not do anything else in the loop. If it does not break and completes all the code in d, then it runs statement c once.
3) repeat steps 2, 3 until 3a is true.
Assuming you mean a for loop:
for (<initialization>; <condition>; <increment>) {
// loop body
}
The initialization is executed first. Then the condition is evaluated, and if it evaluates to true, the loop's body is executed. Once that's done, the increment is executed. Then, the condition is evaluated again, and the whole process repeats until the condition no longer evaluates to true.
for-loop:
initialize->condition->code->increment->condition──false──>end
└───────true───────┘
while-loop:
condition->code->condition──false──>end
└─true─┘
do-while-loop:
code->condition──false──>end
└─true─┘
PS: If you downvote, do it at least for an objective reason. If I made a mistake please tell me.

Categories