ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Home » C programs » C One-D Array programs

C program to reverse array elements

This C program will read N array elements and reverse them, this will print reversed array elements.

Example:

    Input array elements are:
    50, 10, 20, 40, 30

    Output:
    Sorted array elements are:
    30, 40, 20, 10, 50
/*program to reverse array elements.*/ 

#include<stdio.h>
#define MAX 20 

/*	function	:	readArray() 
	to read array elements. 
*/ 

void 	readArray(int a[],int size) 
{ 
	int i; 
	for(i=0;i< size;i++) 
	{ 
		printf("Enter %d element :",i+1); 
		scanf("%d",&a[i]); 
	} 
} 

/*	function	: printArray() 
	to print array elements. 
*/ 
void printArray(int a[],int size) 
{ 
	int i; 
	for(i=0;i < size; i++) 
		printf("%5d",a[i]); 
} 

/*	function	: reverseArray(), 
	to reverse array elements. 
*/ 
void	reverseArray(int a[],int size) 
{ 
	int i,temp; 
	for(i=0;i < size/2; i++) 
	{ 
		temp=a[i]; 
		a[i]=a[((size-1)-i)]; 
		a[((size-1)-i)]=temp; 
	} 
} 

int main() 
{ 
	int arr[MAX]; 
	int n,item,pos; 


	printf("\nEnter size of an Array :"); 
	scanf("%d",&n); 

	printf("\nEnter elements of Array 1:\n"); 
	readArray(arr,n); 
	 
	printf("\nArray elements before reverse :\n"); 
	printArray(arr,n); 

	/* reverse array elements*/ 
	reverseArray(arr,n); 
	printf("\nArray elements After reverse :\n"); 
	printArray(arr,n); 

	printf("\n\n"); 
	return 0; 
} 

    

Outpit

first run (when number of elements are EVEN)
Enter size of an Array :6 

Enter elements of Array 1: 
Enter 1 element :11 
Enter 2 element :22 
Enter 3 element :33 
Enter 4 element :44 
Enter 5 element :55 
Enter 6 element :66 
 
Array elements before reverse : 
   11   22   33   44   55   66 
Array elements After reverse : 
   66   55   44   33   22   11 

second run (when number of elements are ODD)
Enter size of an Array :5 

Enter elements of Array 1: 
Enter 1 element :11 
Enter 2 element :22 
Enter 3 element :33 
Enter 4 element :44 
Enter 5 element :55 

Array elements before reverse : 
   11   22   33   44   55 
Array elements After reverse : 
   55   44   33   22   11 
ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.