Results 1 to 6 of 6
Thread: Can anyone explain this logic?
- 08-31-2011, 09:47 AM #1
Member
- Join Date
- Aug 2011
- Posts
- 3
- Rep Power
- 0
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).
Output:Java 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)); } }
Java Code:kcapkcaB
Last edited by hotsauce; 08-31-2011 at 10:01 AM.
- 08-31-2011, 09:57 AM #2
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
What will print when you compile and run this code?
- 08-31-2011, 01:40 PM #3
Add a println to show the values of the variable n as the loop executes.
- 09-01-2011, 02:08 AM #4
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 #5
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Re: Can anyone explain this logic?
No response from OP for a long time.
- 09-08-2011, 08:21 PM #6
Member
- Join Date
- Aug 2011
- Posts
- 3
- Rep Power
- 0
Similar Threads
-
Need help in logic
By nn12 in forum New To JavaReplies: 3Last Post: 03-23-2011, 06:44 PM -
Need help on logic
By nn12 in forum New To JavaReplies: 6Last Post: 03-10-2011, 11:06 AM -
Please Explain me how i got this output.. I am new to java .. so please Explain me...
By vicky82 in forum New To JavaReplies: 2Last Post: 12-13-2010, 01:34 PM -
Please Explain me how i got this output.. I am new to java .. so please Explain me...
By vicky82 in forum New To JavaReplies: 3Last Post: 12-13-2010, 07:22 AM -
Cant get the logic right
By jermaindefoe in forum New To JavaReplies: 4Last Post: 03-11-2008, 12:22 AM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks