Write a C program to Sort the array in Ascending or Descending Order Using Switch Case.

                             Practice Problems For Beginners-7

Problem Statement:-Write a C program to Sort the array in Ascending or Descending Order Using Switch Case for choice.

Code:- 

#include<stdio.h>
#include<conio.h>
void main()
{
 int a[100],n,i,j,no,tmp;
//Take input from user of how many elements are there in a array
 printf("Array size:");
 scanf("%d", &n);
//Take a input from user the elements of the array
 printf("Elements:");
//using for loop insert all the elements in a array
 for(i=0;i<n;i++)
 {
  scanf("%d", &a[i]);
 }
//using switch case ask the user type of sort
 printf("Enter\n 1 for Ascending order\n 2 for Descending order\n");
 scanf("%d", &no);
 switch(no)
 {
  case 1:for(i=0;i<n;i++)//no of pass
{
  for(j=0;j<n;j++)//no of elements
  {
   if(a[j]>a[i])
   {
    tmp=a[i];
    a[i]=a[j];
    a[j]=tmp;
   }
  }
}
printf("Ascending order: ");
for(i=0;i<n;i++)
{
  printf("%d\t", a[i]);
}
break;
  case 2:for(i=0;i<n;i++)//no of pass
{
  for(j=0;j<n;j++)//no of elements
  {
   if(a[j]<a[i])
   {
    tmp=a[i];
    a[i]=a[j];
    a[j]=tmp;
   }
  }
}
printf("Descending order: ");
for(i=0;i<n;i++)
{
  printf("%d\t", a[i]);
}
break;
  default:printf("Invalid Choice");
 }
 getch();
}

Output:-





Post a Comment

0 Comments