Reputation: 5
I am trying to reverse the array.
#include<stdio.h>
//code to reverse the current array1
void reverse(int array1[]){
int i;
int n=3;
for (i = 0; i <n; i++)
{
array1[i]=array1[n-i-1];
printf("%d\t",array1[i]);
}
}
int main(){
int array1[]={1,2,3};
reverse(array1);
}
result 3 2 3
when i compile this code i am getting 3 in array[0] poistion what is my error?
Upvotes: 0
Views: 50
Reputation: 1
Can't write code right now.
You're overwriting array's value at position 0 on the first loop, so when your code checks the value at position 0 it reads the new value instead of the old one).
Create a second array to write the inverted values instead of overwriting them.
Upvotes: 0
Reputation: 75062
You are reading and writing the same array, so some writing will break data that are not read yet.
Typical way to reverse is to swapping elements in former half and latter half.
void reverse(int array1[]){
int i;
int n=3;
for (i = 0; i <n; i++)
{
if (i < n-i-1) /* avoid swapping the same pair twice */
{
int tmp=array1[i];
array1[i]=array1[n-i-1];
array1[n-i-1]=tmp;
}
printf("%d\t",array1[i]);
}
}
Upvotes: 1