Reversing an array In place

后端 未结 11 905
温柔的废话
温柔的废话 2020-12-21 04:20

Okay so I\'ve tried to print and Array and then reverse is using another array But I\'m trying to create a For Loop that will take an array and reverse all of the elements i

11条回答
  •  遥遥无期
    2020-12-21 05:22

    You can reverse an array in place you don't need an auxiliary array for that, Here is my C code to do that

    #include 
    int main(void)
     {
        int arr[5]={1,2,3,4,5};
        int size=sizeof(arr)/sizeof(int);   
        int success= reverse(arr,size);
        if(success==1)
            printf("Array reversed properly");
        else
            printf("Array reversing failed");   
    
        return 0;
    }
    
    
    int reverse(int arr[], int size)
    {
        int temp=0;
        int i=0;
        if(size==0)
            return 0;
        if(size==1)
            return 1;
    
        int size1=size-1;
        for( i=0;i<(size/2);i++)
        {
            temp=arr[i];
            arr[i]=arr[size1-i];
            arr[size1-i]=temp;
        }
    
        printf("Numbers after reversal are ");
        for(i=0;i

提交回复
热议问题