Showing posts with label Ascending order. Show all posts
Showing posts with label Ascending order. Show all posts

Saturday, August 22, 2015

Sort numbers in Ascending Order

Q. 102. Write a program to accept 'n' integers into an array and sort them in ascending order.




Copy Code:

#include <iostream>
using namespace std;

int main()
{
  int a [50], i, j, n, temp;
  cout << "How many Numbers do you want to Sort ? ";
  cin >> n;
  cout << "\nEnter "<< n <<" Numbers \n";
  for ( i=0 ; i<n ; ++i )
       cin >> a[ i ];

   for ( i=0 ; i < n-1 ; ++i )
      for ( j = i+1 ; j<n; ++j )
          if ( a[ i ] > a[ j ])
               {
                   temp = a[ i ] ; 
                   a[ i ] = a[ j ];
                   a[ j ] = temp;
                }   

  cout << "\nHere is the Sorted List \n";
  for ( i=0 ; i<n ; ++i )
       cout << a[ i ] <<"\n";
  
  return 0;
}





Sort Word List in Ascending Order

Q. 103. C++ Program to accept 'n' Words into an array and Sort them in Ascending order.


Copy Code:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  char a[20][50], tmp[50]; 
  int i, j, n;
  cout << "How many Words to Sort ? ";
  cin >> n;
  
  cout << "\nEnter "<< n <<" Words \n";
  for ( i=0 ; i<n ; ++i )
       cin >> a[i];

  for ( i=0 ; i < n-1 ; ++i )
      for ( j = i+1 ; j<n; ++j )
           if ( strcmp ( a[i], a[j]) > 0 )
               {
                   strcpy ( tmp, a[i] ) ;
                   strcpy ( a[i], a[j] );
                   strcpy ( a[j], tmp );
                }   

  cout << "\nSORTED LIST\n\n";
  for ( i=0 ; i<n ; ++i )
       cout << a[i] <<"\n";
  
  return 0;
}