Posted By:
21 Jun, 2013 9:21 am PDT

Reversing Array elements in C

How can we reverse the elements in an array?
Attachment:None


For example if a is an array of integers with three elements such that a[0] = 1 a[1] = 2 a[2] = 3

 

Then on reversing the array will be a[0] = 3 a[1] = 2 a[0] = 1

 

We copy the elements of array a into array b in reverse and then copy the array b elements into array a which will be in reverse order. We can also reverse the array without using additional memory.

#include <stdio.h>
#include<conio.h>
int main() {
  int array[100], n, c, t, end;
 
  printf("Enter the no of elements\n");
  scanf("%d", &n);
  end = n - 1;
 
 printf("Enter the elements\n");
  for (c = 0; c < n; c++) {
    scanf("%d", &array[c]);
  }
 
  for (c = 0; c < n/2; c++) {
    t          = array[c];
    array[c]   = array[end];
    array[end] = t;
 
    end--;
  }
 
  printf("Reversed array elements are:\n");
 
  for (c = 0; c < n; c++) {
    printf("%d\n", array[c]);
  }
 
  getch();
}

 

Please see the video for more details

Was it useful?  



The following is the program that prints the elements of an array in a reverse order.

 

#include<stdio.h>

#include<conio.h>

int main()

{

int array[10],i,n;

printf("enter the number of elements in the array:");

scanf("%d",&n);

for(i=0;i<n;i++)  // enters elements into array starting at index - 0 to index - (n-1)

scanf("%d",&array[i]);

printf("the reverse ordered array is :");

for(i=n-1;i>=0;i--) // prints elements from array starting at index - (n-1) to index-0.

printf("%d",array[i]);

getch();

}

 

 


Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud