Number Swapping

The Problem

Given an array of numbers, your task is to swap the numbers (except the last one) by one position backward and the last number to be put in the first position. The constraints are that no external temporary variable can be used.

For example if the numbers are a, b, c, d, e then the resulting array should have a->b, b->c, c->d, d->e and e->a.

 

Sample input

The input consists of a line of integers separated by white spaces. The first integer denotes the number of numbers n in the input array. It is followed by n integers to be swapped according to the above rule.

5 12 23 34 45 56

 

Sample output

The output should be the line of swapped integers.

56 12 23 34 45 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace NumberSwapping

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] num = {1, 2, 3, 4, 5, 6, 7, 8 };

            Console.WriteLine("Array before swapping");

            for (int i = 0; i < num.Length; i++)

            {

                Console.Write(num[i] + " ");

            }

            Console.WriteLine();

            if (num.Length > 1)

            {

                Console.WriteLine("Array after swapping");

                //Swapping the first and the last element in the array

                num[0] = num[0] + num[num.Length – 1];

                num[num.Length – 1] = num[0] – num[num.Length – 1];

                num[0] = num[0] – num[num.Length – 1];

                for (int i = num.Length – 1; i > 1; i–)

                {

                    //Swapping the first and the last element in the array

                    num[i] = num[i] + num[i – 1];

                    num[i – 1] = num[i] – num[i – 1];

                    num[i] = num[i] – num[i – 1];

                }

                for (int i = 0; i < num.Length; i++)

                {

                    Console.Write(num[i] + " ");

                }

                Console.WriteLine();

            }

            else

            {

                Console.WriteLine("Insufficient number of elements: Can’t swap.");

            }

        }

    }

}

 

Array before swapping
1 2 3 4 5 6 7 8
Array after swapping
8 1 2 3 4 5 6 7
Press any key to continue . . .

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s