# Swap Two Integers

A student reproduced a programming question for me today:

Write a program which accepts 2 integers separated by a space. If the first integer is less than the second integer, output a message stating this fact e.g “The first number is smaller”, else swap the values of both variables which contain the integers respectively.

Before the program exits, print both integers respectively.

# Analysis

A flowchart for the solution is shown below. Note that, input is obtained on separate lines, a limitation of the software used to create the chart, flowgorithm:

# Solution 1

Below is a suggested solution written in pascal code:

Copy-able pascal code here:

program swap;
uses crt;
var
num1,num2,temp:integer;

begin

writeln(‘Please enter 2 unequal integers separated by a space…’) ;
//read data separated by a space

if (num1>num2) then //we swap the numbers using a tempoary varible
begin
temp:=num1;
num1:=num2;
num2:=temp;
end //notice that there is no semicolon on this line.
else//print message
writeln(‘num1 is less than num2’);

writeln();
writeln(num1,’ ‘,num2) ;

writeln(‘Press any key to exit…’);
end.

# Solution 2

Below is a suggested solution written in c# code (generated by flowgorithm and edited to accept input of the two integers on one line):

Copy-able c# code here:

using System;

public class Program
{
public static void Main()
{

int num1, num2, temp;
string anykey;

Console.WriteLine(“Please enter 2 unequal integers separated by a space…”);

//Read line, and split it by whitespace into an array of strings
//Parse element 0
num1 = int.Parse(tokens[0]);
//Parse element 1
num2 = int.Parse(tokens[1]);

if (num1 > num2)
{
temp = num1;
num1 = num2;
num2 = temp;
}
else
{
Console.WriteLine(“num1 is less than num2” + “\n”);
}
Console.WriteLine(num1 + ” ” + num2 + “\n”);
Console.WriteLine(“Press any key to exit.” + “\n”);