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++;
}
}
A while loop may be easier to conceptualize. Think of it as starting from both ends and swapping the two elements until you hit the middle.
i = len - 1;
j = 0;
while(i > j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i--;
j++;
}
//Output contents of now-reversed array.
for(i = 0; i < len; i++)
printf("%d ", a[i])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With