Aug 9, 2013 at 4:27am UTC
Can someone explain me this piece of code? it's supposed to reverse the element of an array. I dont understand the loop thats being used.
for(i = 0,j = n - 1; i < n/2; i++, j--)
{
temp=Arr[i];
Arr[i]=Arr[j];
Arr[j]=temp;
}
Aug 9, 2013 at 4:39am UTC
swaps the first and last element,
swaps the second and last but one element
..
so on till the middle element is reached by then the array would be reversed.
ex1:
12345
52341
54321
ex:2
123456
623451
653421
654321
Aug 9, 2013 at 4:44am UTC
i = 0 is the position of the first element in the array
n is the lenght of the array
n - 1 is the position of the last element in the array
i < n/2 means to loop until i is equal or greater to half the lenght (meaning that Arr[i] refers to the element in the middle of the array)
temp = Arr[i] stores a copy of Arr[i] because the original will be lost in the next line
Arr[i] = Arr[j] assigns to Arr[i] the value of Arr[j] (e.g. in the first iteration it assigns the value of the last element to the first)
Arr[j] = temp assigns to Arr[j] the value of Arr[i]
i++ makes i refer to the following element in the array
j -- makes j refer to the previous element in the array