Thursday, July 30, 2009

Am really failing to see my error here help me with this Implement a function in C?

that takes an array of integers,%26amp; and reverses the order of items in the array?void reverse_order(int array[], int n)


{


/* your code .


*/


}


You should then implement a main() function which reads in a set of integers into an array,


reverses the order of the number (using the function you have just defined) and prints them out


again.


#include%26lt;stdio.h%26gt;


#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;





void reverse_order(int[],int);





void main()


{


int a[10],n,i;


clrscr();





printf("\nEnter the No. of Elements : ");


scanf("%d",%26amp;n);





printf("\nEnter the Elements One by One :\n");


for(i=0;i%26lt;n;i++)


scanf("%d",%26amp;a[i]); // Read Array





printf("\nGiven Elements are : ");


for(i=0;i%26lt;n;i++)


printf(" %d ",a[i]); // Print Before Reversed





reverse_order(a,n); // Call Fn.





printf("\nAfter Reversed : ");


for(i=0;i%26lt;n;i++)


printf(" %d ",a[i]); // Print After Reversed





getch();


}

Am really failing to see my error here help me with this Implement a function in C?
Well, there are a couple picky things, but here's the one that really stands out: YOU HAVEN'T WRITTEN THE FUNCTION. It has no content and no function.





And, main() should return an int.





How's that for a start? ;-) Here's what I threw together:





void reverse_order(int array[], int n)


{


int reverse[n], i;


for (i = n; i %26gt;= 1; i--)


reverse[n-i] = array[i-1];





for (i = 0; i %26lt; n; i++)


array[i] = reverse[i];


}





I thought I could do this in four lines by just having


array = reverse;


after the first loop, but realized it wouldn't work that way since the scope of reverse is local to the function. So instead, you have to copy reverse over value by value (thus the second loop).





Also, I thought about swapping first and last with a temp int like the person below me, but with the checking you'd have to do if was odd vs. even, I figured this would be shorter. Not to mention, it's straightforward.
Reply:To reverse the content of an array swap the first element with the last element, the second element with the second to the last element.





stop = n/2 - 1;





for (i = 0; i %26lt;= stop; i++) {





tmp = a[i];


a[i] = a[n-i-1];


a[n-i-1] = tmp;





}
Reply:Why did you include stdio.h twice?





Also, it's really hard to read your program without the proper whitespacing (tabs and indents). Paste the code to rafb.net and link to it, so I can actually read it =P


No comments:

Post a Comment