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:

Swap - Main

Solution 1

Below is a suggested solution written in pascal code:

Swapping 2 variables

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
readln (num1,num2);

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…’);
readkey;
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):

Swap - C# Code

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
string[] tokens = Console.ReadLine().Split();
//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”);
anykey = Console.ReadLine();
}
}
© 2018 Vedesh Kungebeharry. All rights reserved

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s