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); */
Solution Steps. Place the two pointers (let start and end ) at the start and end of the array. Swap arr[start] and arr[end] Increment start and decrement end with 1. If start reached to the value length/2 or start ≥ end , then terminate otherwise repeat from step 2.
Using SwappingInstead, we reverse the original array itself. In this method, we swap the elements of the array. The first element is swapped with the last element. The second element is swapped with the last but one element and so on.
To print an array in reverse order, we shall know the length of the array in advance. Then we can start an iteration from length value of array to zero and in each iteration we can print value of array index. This array index should be derived directly from iteration itself.
#include <stdio.h> int main() { int n, reverse = 0, remainder; printf("Enter an integer: "); scanf("%d", &n); while (n != 0) { remainder = n % 10; reverse = reverse * 10 + remainder; n /= 10; } printf("Reversed number = %d", reverse); return 0; } Run Code.
void reverse(char, int); //declaration wrong
void reverse(char[], int);
^^^
Your loop
for ( i = 0; i >= n ; i++) // this fails i=0, n=some size
should be
for ( i = 0; i <= n ; i++)
Avoid using gets()
use fgets()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With