Can anyone explain this logic?

• 08-31-2011, 09:47 AM
hotsauce
Can anyone explain this logic?
This part of the program takes a string and print each letter on a single line, while speaking the string backwards.

To termination the For loop in the printBackwards method it's n>= 0. I originally thought it would be n==0, but using n==0 the compiler just terminates the program. I was only able to get it to work through trial and error (n>=0).

Code:

```        public static void main(String[] args) {                                 String word = "Backpack";                                 printBackwards(word);         } public static void printBackwards (String s){                         for ( int n = length(s) - 1; n >= 0; n--){                         System.out.println(s.charAt(n));                                         }         }```
Output:
Code:

`kcapkcaB`
• 08-31-2011, 09:57 AM
Eranga
What will print when you compile and run this code?
• 08-31-2011, 01:40 PM
Norm
Add a println to show the values of the variable n as the loop executes.
• 09-01-2011, 02:08 AM
Junky
Quote:

Originally Posted by hotsauce
I originally thought it would be n==0

If you used that as the condition it means that the loop would only execute if n IS zero. There are 3 possibilities.

Initial value of n is zero. Condition is true. Execute loop. Change value of n. Condition is false. Exit. Loop only executes once which is pointless.

Initial value of n is zero. Condition is true. Execute loop. Never change value of n. Condition is true. Endless loop. Not very useful either.

Initial value of n is not zero. Condition is false. Never executes loop. Yet again a pointless loop.
• 09-06-2011, 06:47 AM
Eranga
Re: Can anyone explain this logic?
No response from OP for a long time.
• 09-08-2011, 08:21 PM
hotsauce
Re: Can anyone explain this logic?
No, I'm still here. Didn't have internet for awhile.

Thanks for the explanation, it really helped.