Reputation: 3
I have this code below which writes a word backward, I understand everything but one little detail in the for loop: for (int i = 0; i < numberOfChars /2; i++). What does the "/2" do and why does it only work with it?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h> // time
void reverse(char array[], int numberOfChars) {
for (int i = 0; i < numberOfChars /2; i++) {
char tmp;
tmp = array[i];
array[i] = array[numberOfChars - i - 1];
array[numberOfChars - i - 1] = tmp;
}
}
int main(void) {
char word[55];
int howMany;
printf("Please enter a word:\n");
scanf_s("%s", word, sizeof(word));
printf("how many char do you want to reverse?\n");
scanf_s("%d", &howMany);
reverse(word, howMany);
printf("New arr:%s\n", word);
return 0;
}
Upvotes: 0
Views: 933
Reputation: 20901
The division halves the array. When you track the algorithm, it swaps one from left hand side, the other is from right hand side. For even size, every number is exchanged. For odd size, same like evens except by the middle one stayed at its same place. When I encountered the algorithm, I solved it using a paper and pen. Because the way more effective to get its logic. Here is the depicted explanation. As a result, if it isn't halved, firstly reversed up to half of the array, then reversed again so stayed as same order.
Upvotes: 0
Reputation: 69934
As Ryan pointed out in a comment, if you do not include the /2
each position in the array gets swapped twice, and goes right back to where it started. For example, if you have 5 elements, it does this:
swap 0 with 4
swap 1 with 3
swap 2 with 2
swap 3 with 1
swap 4 with 0
By the way, I think this code gets clearer if you use two indices to iterate over the array instead of one:
int i=0;
int j=numberOfChars-1;
while(i < j){
char tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
Upvotes: 1
Reputation: 1122
Because with this code, you put the start in the end, and the end in the start of your string. So, when you run a half of the "howMany" char's your user wants to change, it has already changed it at all.
Upvotes: 0