Thursday, July 9, 2009

Antoher C array question...?

Write a function that reverses the elements of an arry so that the last element becomes the first, the second from the last becomes the second, and so forth. the function is to reverse the elements in place w/o using another array, but u can use a variable to hold an element temporarily. then write a test driver(idk wat that is?) to test ur function. test it twice, once with an even # of elemnts in the array and once with an odd # of elemnts in the array.

Antoher C array question...?
#include "stdio.h"


#include "malloc.h"


int main(void){


int *a; /* The array */


int i, j, l = 10; /* Start, End and Length */


do{


a = (int *)malloc(sizeof(int)*l); /* Allocate space on the heap */


printf("sizeof(a)==%d which is equal to %d ints.\n", sizeof(int)*l, l);


j=l-1;


for(i=j;i%26gt;=0;a[i]=i--){}


i=0;


for(;i%26lt;l/2;i++, j--){ /* While we have elements left to swap */


printf("a[%d]==%d, a[%d]==%d -%26gt; ", i, a[i], j, a[j]);


a[i] ^= a[j]; /* No other variable used to swap elements */


a[j] ^= a[i];


a[i] ^= a[j];


printf("a[%d]==%d, a[%d]==%d.\n", i, a[i], j, a[j]); /* Show that we swapped the elements */


}


free(a); /* Release the array back to the heap*/


l++; /* Increment the length of the array */


} while(l%26amp;2); /* Until the length of the array is even again */


printf("All done.\n");


return 0;


}





Good luck with your coding (0;
Reply:Again...enough to get you off to a fast start...








int array[10]={0,1,2,3,4,5,6,7,8,9};





reverse()


{


int k,j;


for(k=0; k%26lt;10; k++)


{


//swap....


j = array[k];


array[k] =array[9-k];


array[9-k] =j;


}


}





testfunc()


{


puts("Numbers should appear in descending order");


for(k=0; k%26lt;10; k++)


printf("%d\n", array[k]);





}





/* A shame...lokal2b (answer just below this) presented a very clever solution using exclusive or, but even he got a thumbs down and no thanks. Tough crowd. :-) */


No comments:

Post a Comment