+ 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); } }
9 Respostas
+ 2
đ
°đ
č đ
đ
đ
đ
đ
Ł you mean writing the answer?
+ 2
đ
°đ
č đ
đ
đ
đ
đ
Ł thanks for the help
+ 1
Someone please answer
+ 1
đ
°đ
č đ
đ
đ
đ
đ
Ł thanks but in general -1 shows exception why not here?
+ 1
And why j is not decremented once
- 1
Atul
Writing.....
- 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
- 1
Atul
Why it will show exception? We can assign negative value too.
- 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