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 in place without me having to go through the process of creating an entirely new array.
My for loop is running into some problems and I'm not sure where to go from here...i'm using i to take the element at the end and move it to the front and then j is being used as a counter to keep track of the elements...if there is an easier way to do this Any suggestions would be appreciated.
I'm New to this programming language so any extra info is greatly appreciated.
#include <stdlib.h>
#include <time.h>
int Random(int Max) {
return ( rand() % Max)+ 1;
}
void main() {
const int len = 8;
int a[len];
int i;
int j = 0;
Randomize() ;
srand(time(0));
//Fill the Array
for (i = 0; i < len; ++i) {
a[i] = rand() % 100;
}
//Print the array after filled
for (i = 0; i < len; ++i) {
printf("%d ", a[i]);
}
printf("\n");
getchar();
//Reversing the array in place.
for (i = a[len] -1; i >= 0, --i;) {
a[i] = a[j];
printf("%d ", a[j]);
j++;
}
}
You are on the right track but need to think about that last for loop a little more and the assignment operation inside. The loop initialization is off, since
i = a[len] - 1
will copy the value of the last entry toi
. Since that value is a random number, your index will probably start out of bounds.Next, you're copying half of the array to the other half and then back. That loop does the following:
a[7] = a[0] a[6] = a[1] a[5] = a[2] a[4] = a[3] ...
At this point you've lost all of the initial values in a[4] through a[7].
Try this:
Use a debugger and step through the loop watching the value of
i
,temp
, and each element in the arrayYou can reverse an array in place you don't need an auxiliary array for that, Here is my C code to do that
For starters, instead of this:
you want this:
but you also only want to go half-way through the array, so it would be
Just my 2 cents...
Try this;
Hope this helps... :)
Just for suggestion. Try to use meaningful variable name instead of just
i,a...
. That will help you while writing a bigger code. :)