Pages

Custom Search

Thursday, October 17, 2013

Reversing array contents in the same array.

Reversing array contents:

In this program, we have to reverse the array contents without using any temporary array.
This can be achieved using swapping technique.
Have one index 'i' pointing to first element and one index 'j' pointing to last element.
Swap their contents.
Increment i, decrement j
Continue as long as i is less than or equal to j.
Done.
Print the array contents again, which are now in reverse order.


Source Code:



1:  #include <stdio.h>  
2:  #include <stdlib.h>  
3:    
4:  int main()  
5:  {  
6:       int i, a[10], t, n, j;  
7:         
8:       printf("\nEnter the size of the array: ");  
9:       scanf("%d", &n);  
10:         
11:       printf("\nEnter the array elements: ");  
12:       for(i=0;i<n;i++)  
13:            scanf("%d", &a[i]);  
14:              
15:       for(i=0,j=n-1;i<=j;i++,j--)  
16:       {  
17:            t=a[i];  
18:            a[i]=a[j];  
19:            a[j]=t;  
20:       }  
21:         
22:       printf("\nThe reverse of the array is: ");  
23:       for(i=0;i<n;i++)  
24:            printf("%d ", a[i]);  
25:       printf("\n");  
26:         
27:       return 1;  
28:  }  


Custom Search