Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing Array in C?

Tags:

c

reverse

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); */
like image 742
JoC Avatar asked Oct 11 '13 03:10

JoC


People also ask

What is reversing in array?

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.

Can we reverse arrays?

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.

How do I print an array in reverse order?

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.

What is reversing in C?

#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.


1 Answers

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.

like image 139
Gangadhar Avatar answered Sep 20 '22 05:09

Gangadhar