+ 1

Can anyone explain me what is happening in the I and j loops?

public class Program {static void pattern(String n){ int c=0; String s=""; String a=""; for(int i=-1;i<n.length();i++){ c++; for(int j=n.length()-1;j>n.length()-c;j--){ s=(n.charAt(j)+""+n.charAt(i)); a=""+s; } System.out.print (a);; } System.out.print ("");} public static void main(String[] args) { String n="house" ; pattern(n); } }

15th May 2021, 8:49 PM
Atul [Inactive]
9 Answers
+ 2
🅰🅹 🅐🅝🅐🅝🅣 you mean writing the answer?
16th May 2021, 5:51 AM
Atul [Inactive]
+ 2
🅰🅹 🅐🅝🅐🅝🅣 thanks for the help
16th May 2021, 1:42 PM
Atul [Inactive]
+ 1
Someone please answer
16th May 2021, 3:40 AM
Atul [Inactive]
+ 1
🅰🅹 🅐🅝🅐🅝🅣 thanks but in general -1 shows exception why not here?
16th May 2021, 6:19 AM
Atul [Inactive]
+ 1
And why j is not decremented once
16th May 2021, 6:20 AM
Atul [Inactive]
- 1
Atul Writing.....
16th May 2021, 5:35 AM
A͢J
A͢J - avatar
- 1
Atul In this code it is happening like this: n = "house" here i start from -1 and j start from n.length() - 1 means j = 4 till j > (5 - 1) So for i = -1, j = 4; j > 4 nothing will happen now for i = 0, j = 4; j > 3 s = n.charAt(4) + ""+ n.charAt(0) = eh a = eh System.out.print(a) // will print eh ------------ for i = 1 Inner loop will work two times but only last value will be print now for i = 1, j = 4, j > 2, j-- s = n.charAt(4) + "" + n.charAt(1) = eo a = eo; for i = 1, j = 3, j > 2, j-- s = n.charAt(3) + "" + n.charAt(1) = so System.out.print(a) // will print so ------------------ And so on.... so finally it is ehsou and then reversing it oushe Finally we get ehsououshe
16th May 2021, 6:14 AM
A͢J
A͢J - avatar
- 1
Atul Why it will show exception? We can assign negative value too.
16th May 2021, 6:20 AM
A͢J
A͢J - avatar
- 1
Atul j is decrementing but depending on c variable For 1st iteration of outer loop c will be 1 but j = 4; j > 4 so in this case j will not decrement But after 2nd iteration of outer loop c will be 2 so inner will look like this: for (j = 4; j > (5 - 2); j--) here j will be decrement
16th May 2021, 6:24 AM
A͢J
A͢J - avatar