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++;
}
}
call it to reverse array
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.
Here's an easy and clean function for flipping arrays of all sizes. Change the parameters according to your type of array:
If you are not interesting in writing functions for any numeric type, try macros for this task. This code same working with any built-in numeric type: int, float, double.
It has not a support for strings, since any string is ending on the character the NULL character '\0'. More a controlled version my similar answer is here https://stackoverflow.com/a/42063309/6003870 and contains solution for reverse a string.
A full code
I am used the GCC for compilation and your result must be as next
Testing environment