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

Getting Set Up For C# Programming

C# programming  can be achieved by using Microsoft Visual Studio.  Below are some steps for setup:


  1. Visit https://www.visualstudio.com/downloads/
  2. Download and run the installer for Visual Studio Community Edition :

VS 01


3. The installer configures the installation…….

VS 02

…..and sets itself up for the main installation of visual studio.

VS 03


4. Next, you will be faced with installation options.  For now, select all options as shown below, and click on install:

VS 04

Visual studio will now be downloaded and installed.

VS 05


5. After Installation, when you run Visual Studio, you will be faced with a login screen:
VS 06

 

If you have an existing Microsoft account you can sign in.

Otherwise, you will need to create one then login.

From here on, you can start using visual studio 🙂

 

© 2018  Vedesh Kungebeharry. All rights reserved