C program to reverse an array

C program to reverse an array

In this article we are going to discuss how to reverse an array, so to reverse an array we have to understand the concept first, so we are going to discuss the concept of the array and then we are going to see how we can apply this concept in our program.

For example :

Input :

we are taking int size arr[] = { 1, 2, 3, 4, 5, 6}
So basically the size of the array is 6,

apply the size formula of the array to calculate the length of the array that is –

int n = sizeof(arr)/sizeof(int);

Logic :

then we are going to use a loop to swap these numbers.

for(int i = 0; i<n/2; i++){
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;

then we simply print the arr[i]

output :

according to our example, our output will be :

12, 3, 4, 2, 7, 8, 9,

we are going to swap the first element to the last element of the array by using the swap method. So two swap two numbers we simply use the third variable in our program. So let’s start to implement this method in our program.

Example 1:

// C program to to reverse an array

#include <stdio.h>
int main(){

int arr[] = {9, 8, 7, 2, 4, 3, 12};
int temp;

int n = sizeof(arr)/sizeof(int);

for(int i = 0; i<n/2; i++){
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
for(int i = 0; i < n; i++){
printf(“%d ,”, arr[i]);
}
}

Output

12, 3, 4, 2, 7, 8, 9,

In the above program, we simply understand how we can reverse the array by using the swap method, so now we are going to see another example of this in the next example we are going to change the value of the array and then swap the numbers. So let’s start!

// C program to reverse an array

#include <stdio.h>
int main(){

int arr[] = {1,2,3,4,5,6,7,8,9};
int temp;

int n = sizeof(arr)/sizeof(int);

for(int i = 0; i<n/2; i++){
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}

printf(“The numbers after swapping are:”);
for(int i = 0; i < n; i++){
printf(” %d ,”, arr[i]);
}

}

output

The numbers after swapping are: 9, 8, 7, 6, 5, 4, 3, 2, 1,

So, In this way, we simply understand how to reverse an array. I hope this concept is clear to you now, you can also explore these programs by giving different values. Until then keep learning, and keep exploring!