Skip to content

Commit 5a2ea17

Browse files
committed
feat: Reverse copy an array by iterating from end of source to beginning
🧠 Logic: - Given array `A` is copied into array `B` in reverse order. - Loop runs from end of `A` (`A.length-1`) to start, while inserting into `B` from index 0 onward. - Demonstrates how to reverse an array during the copy process. - Final result is printed using an enhanced for-loop. Signed-off-by: Somesh diwan <[email protected]>
1 parent ed7637f commit 5a2ea17

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed
Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,41 @@
11
public class ReverseCopyingArray {
2-
public static void main(String[] args)
3-
{
2+
public static void main(String[] args) {
43
int A[]={8,6,10,9,2,15,7,13,14,11};
54
int B[]=new int[10];
65

7-
for(int i=A.length-1,j=0;i>=0;i--,j++)
8-
{
6+
for(int i=A.length-1,j=0;i>=0;i--,j++) {
97
B[j]=A[i];
108
}
11-
for(int x:B)
12-
{
9+
for(int x:B) {
1310
System.out.print(x+",");
1411
}
1512
}
1613
}
14+
15+
/*
16+
1. Initialization part: `int i=A.length-1,j=0`
17+
- Creates two counters in one statement
18+
- starts from the last index of array A (A.length-1) `i`
19+
- starts from 0 `j`
20+
21+
2. **Condition part** : `i>=0`
22+
- Loop continues as long as is greater than or equal to 0 `i`
23+
- Only checks, since will naturally stay within bounds `i``j`
24+
25+
3. Increment/Decrement part: `i--,j++`
26+
- decrements by 1 in each iteration (moves backwards) `i`
27+
- increments by 1 in each iteration (moves forwards) `j`
28+
29+
4. Loop body: `B[j]=A[i]`
30+
- Copies element from position of array A to position of array B `i``j`
31+
32+
Here's how it works step by step:
33+
34+
Iteration 1: i=9, j=0 → B[0] = A[9]
35+
Iteration 2: i=8, j=1 → B[1] = A[8]
36+
Iteration 3: i=7, j=2 → B[2] = A[7]
37+
...and so on
38+
39+
This is a compact way of writing two counters moving in opposite directions.
40+
It could also be written as two separate loops or with just one counter, but this is more efficient as it does the job in a single pass.
41+
*/

0 commit comments

Comments
 (0)