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 i
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 to i
. 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:
for( i = 0; i < len / 2; i++ ){
int temp = a[i];
a[i] = a[len - i];
a[len - i] = temp;
}
Use a debugger and step through the loop watching the value of i
, temp
, and each element in the array
For starters, instead of this:
for (i = a[len] -1; i >= 0, --i;) {
you want this:
for (i = len-1; i >= 0, --i;) {
but you also only want to go half-way through the array, so it would be
for (i = len-1; i > j, --i;) {
#include<stdio.h>
void main() {
int array[] = {0,1,2,3,4,5,6,7,8,9,10,12,13};
int i,j;
unsigned long int len = sizeof(array)/sizeof(array[i]);
for(i=0; i<len/2; i++) {
j = array[i];
array[i] = array[(len-1)-i];
array[(len-1)-i] = j;
}
for(i=0; i<len; i++) printf("%d ",array[i]);
printf("\n");
}
#include<Stdio.h>
#include<string.h>
#define max 25
int main()
{
char arr[max]="0123456789";
strrev(arr);
atoi(arr);
return 0;
}
//you can also use built in functions such as strrev(); string reverse atoi just
//changes string into integer
void reverse_range(int* buffer, int left, int right)
{
while (left < right)
{
int temp = buffer[left];
buffer[left++] = buffer[right];
buffer[right--] = temp;
}
}
call it to reverse array
int a[3] = {1, 2, 3};
reverse_range(a, 0, 2);
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])