Arrays

Usually we use an array because we want to access the array in a different order.

The program below reads in three numbers, sorts them, and then prints them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//Arrays: Read 3 numbers, sort and print
#include<iostream>
using namespace std;
void swap(double&, double&);
int main() {
   double num[3];
   for(int i=0;i<3;i++) {
     cout<<"Enter a number: ";
     cin>>num[i];
   }
   if (num[0] > num[1]) swap(num[0], num[1]);
   if (num[1] > num[2]) swap(num[1],num[2]);
   if (num[0] > num[1]) swap(num[0], num[1]);
   for(int i=0;i<3;i++) {
     cout<<num[i]<<endl;
   }
   system("pause");
   return 0;
} //main
void swap(double &n1, double &n2) { //receives n1 and n2 by reference, swaps them
  double temp;
  temp=n1;
  n1=n2;
  n2=temp;
} //swap
CODE

This algorithm works for just 3 numbers. You will study other algorithms for sorting large arrays.

NEXT: Names of Months