Sunday, May 9, 2021

Reverse elements in Array

 This example will show you how to reverse elements in an Array using C program.

Reverse elements in Array


The below reverse function takes two arguments.

void reverse(int *a, int n)


*a – pointer to an array

n – size of the array


Example

#include<stdio.h>

void reverse(int *a, int n){
	int j,l,i;
	for(j=0;j<n/2;j++){
		l = a[j];
		a[j] = a[n-j-1];
		a[n-j-1]=l;
	}
	for(i=0;i<n;i++){
		printf("a[%d]=%d ",i,a[i]);
	}
}

main(){
	int i;
	int size=5;
	int a[5];
	for(i=0;i<size;i++){
		a[i]=i+100;
	}
	reverse(a,size);
	return;
}


Output

a[0]=104 a[1]=103 a[2]=102 a[3]=101 a[4]=100


No comments:

Post a Comment