Control structure: if / else

This example reads in two numbers. If the numbers are not in order, it swaps them, and then prints them out in order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Input two numbers print out in order
#include <iostream>
using namespace std;
int main(){ 
  int num1,num2,temp; 
  //temp will store one of the numbers to swap 
  cout<<"Enter a number:";
  cin>>num1;
  cout<<"Enter another number:";
  cin>>num2;
  if (num1 > num2) { //swap
    temp=num1;
    num1=num2;
    num2=temp;
  } //the numbers are now in order
  cout<<"The smaller number is "<<num1<<"\n";
  cout<<"The larger number is "<<num2<<"\n";
  system("pause");
  return 0;
} //main
CODE

order

In order for the swap to work a third variable is needed. The statements num1=num2; num2=num1; won’t work. Try it, afterwards both numbers will be the same. Which of the original numbers will they both equal?

There is no else, we only swap if the numbers are not in order.

NEXT: Calculate tip based on service