Hi i trying to implement a reverse array code but it doesnt seem to work and im really not sure why. The For loop just doesnt seem to work. I dont know why because the logic seems pretty right to me.
#include <stdio.h>
#include <string.h>
void reverse(char, int);
int main()
{
char a[100];
gets(a);
reverse(a, strlen(a)-1);
printf("%s\n",a);
getchar();
getchar();
getchar();
return 0;
}
void reverse(char ar[], int n)
{
char c;
int i = 0;
printf("n = %d" , n);
for ( i = 0; i >= n ; i++){
c = ar[i];
ar[i] = ar[n];
ar[n] = c;
printf("Processed");
n--;}
}
/*
if (begin >= n)
return;
c = *(x+begin);
*(x+begin) = *(x+n);
*(x+n) = c;
offs = x++;
printf("Begin = %d , n = %d, offs = %p \n", begin, n, offs);
reverse(x, ++begin, --n); */
Your loop
should be
Avoid using
gets()
usefgets()
instead.I think better use macro for this task. In code below it is a macro SWAP.
Content a file main.c
Compilation as:
Result:
Notes:
Based on
4.1 Define a preprocessor macro swap(t, x, y)
4.2 Reversing an array In place
4.3 The answers on this question
Testing environment
for loop condition should be 'i < n'. and prototype declaration should match.
for loop condition should be 'i < n'. and prototype declaration should match.
and "int n" is the size of array. So "i<=n" would make the same array reversed from end to mid, and again from mid to top. So result is same as array. make "n" as half of the array size.