Prints values in array in descending order. - C++ Data Type

C++ examples for Data Type:Array

Description

Prints values in array in descending order.

Demo Code

const int MAX = 10;
#include <iostream>
using namespace std;
#include <stdlib.h>
void fill_array(int ara[MAX]);
void print_array(int ara[MAX]);
void sort_array(int ara[MAX]);
void main()//from www . j a  v a 2  s .  com
{
   int ara[MAX];
   fill_array(ara);    // Puts random numbers in the array.
   cout << "Here are the unsorted numbers:\n";
   print_array(ara);          // Prints the unsorted array.
   sort_array(ara);                     // Sorts the array.
   cout << "\n\nHere are the sorted numbers:\n";
   print_array(ara);      // Prints the newly sorted array.
   return;
}
void fill_array(int ara[MAX])
{
   // Puts random numbers in the array.
   int ctr;
   for (ctr=0; ctr<MAX; ctr++)
   {
      ara[ctr] = (rand() % 100);
   }      // Forces number to 0-99 range.
   return;
}
void print_array(int ara[MAX])
{
   // Prints the array
   int ctr;
   for (ctr=0; ctr<MAX; ctr++)
   {
      cout << ara[ctr] << "\n";
   }
   return;
}
void sort_array(int ara[MAX])
{
   // Sorts the array.
   int temp;            // Temporary variable to swap with.
   int ctr1, ctr2;           // Need two loop counters to swap pairs of numbers.
   for (ctr1=0; ctr1<(MAX-1); ctr1++)
   {
      for (ctr2=(ctr1+1); ctr2<MAX; ctr2++) // Test pairs
      {
         if (ara[ctr1] < ara[ctr2]) // Swap if this
         {
            temp = ara[ctr1]; // pair is not in order.
            ara[ctr1] = ara[ctr2];
            ara[ctr2] = temp;  // "Float" the lowest to the highest.
         }
      }
   }
   return;
}

Result


Related Tutorials