In: Computer Science
Write C program that reorders elements of an array of integers such that the new order is in descending order (first number being the largest). Must have a main function and a swap function.
- int main() will declare an array with the values { 32, 110, 79, 18, 22, 2}. This array will be passed to the swap function.
- the void swap function will perform the necessary operations to reorder the elements of the array.
- After swap() is finished, have main() print the original array to show the new element order.
Code:
#include<stdio.h>
void swap(int array[])
{
int n=6,i=0,j=0;/*initialized the variables*/
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{/*in this loop we sort the array
in the descending order*/
if(array[j]<array[j+1])
{/*Here we swap
the array of the element is greater than
the previous elemet*/
int x = array[j];
array[j] = array[j + 1];
array[j + 1] = x;
}
}
}
printf("New order of elements: ");
for(i=0;i<n;i++)
{
printf("%d ",array[i]);
}
/*HEre we print the array after sorting in descending
order*/
}
int main()
{
int arr[6]={32,110,79,18,22,2},i;/*initialized the
variables*/
printf("Original array: ");
for(i=0;i<6;i++)
{
printf("%d ",arr[i]);
}/*Printing the array before calling the
function*/
printf("\n");
swap(arr);
/*Calling the function*/
}
Output:
Indentation: