Nasif Imtiaz Ohi
Nasif Imtiaz Ohi

Reputation: 1713

using array as function parameter

i am a beginner in c. i don't know that much how to use arrays as function parameters, arguments or how to return array from an function. to my knowledge, the below code should work fine. But i can't get where the problem is. the function is not working as it should.

//reversing an array using function
#include<stdio.h>
void rev(int array[],int length)
{
    int k,j,temp;
    for(k=length-1,j=0;k>=0&&j<length;k--,j++){
        temp=array[k];
        array[k]=array[j];
        array[j]=temp;
    }
}
int main()
{
    int c,arr[]={1,2,3,4,5,6,7,8,9};
    rev(arr,9);
    for(c=0;c<9;c++){
        printf("%d ",arr[c]);
    }
    return 0;
}

Upvotes: 1

Views: 4745

Answers (3)

Boris Ivanov
Boris Ivanov

Reputation: 4254

There no problem with array. Problem with your algo. //reversing an array using function

#include<stdio.h>
void rev(int array[],int length)
{
    int k,j,temp;
    for(k=length-1,j=0;k>=0 && j<length / 2; k--,j++){
        temp=array[k];
        array[k]=array[j];
        array[j]=temp;
    }
}

This reverse array. Your algo reverse it twice. So just add /2 in for conditions.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272257

It looks to me like you're performing the reverse twice.

That is, you swap the beginning and end elements immediately, and at the end of your iteration you swap them again. i.e. you end up with the same array.

You can either:

  1. perform your swap only halfway through your array, or
  2. populate a second array in reverse from the first (I don't know if you want to repopulate the original array, however - you may need to copy it back in)

Upvotes: 0

MByD
MByD

Reputation: 137312

You only need to go until the middle of the array, if you go more, you re-reverse the array:

So this:

for(k=length-1,j=0;k>=0&&j<length;k--,j++){

Should be:

for(k=length-1,j=0;k > j;k--,j++){

Upvotes: 3

Related Questions