This program reverses the array elements. 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
Given below is the c code to reverse an array.
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
Given below is the c code to reverse an array.
C programming code
#include <stdio.h>
#include<conio.h>
void main()
{
int n, c, d, a[100], b[100];
clrscr();
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for (c = 0; c < n ; c++)
scanf("%d", &a[c]);
for (c = n - 1, d = 0; c >= 0; c--, d++)
b[d] = a[c];
for (c = 0; c < n; c++)
a[c] = b[c];
printf("Reverse array is\n");
for (c = 0; c < n; c++)
printf("%d\n", a[c]);
getch();
}
Output of program:
Reverse array by swapping (without using additional memory)
#include <stdio.h>
#include<conio.h>
void main()
{
int array[100], n, c, temp, end;
clrscr();
scanf("%d", &n);
end = n - 1;
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
}
for (c = 0; c < n/2; c++)
{
temp = array[c];
array[c] = array[end];
array[end] = temp;
end--;
}
printf("Reversed array elements are:\n");
for (c = 0; c < n; c++) {
printf("%d\n", array[c]);
}
getch();
}
No comments:
Post a Comment