Monday, January 4, 2010

Numbers 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 




// Numbers Swapping.cpp : Defines the entry point for the console application.

//


 


#include "stdafx.h"


 


 


int _tmain(int argc, _TCHAR* argv[])


{

 int A[100],n,i,j;



//A[100] is the array to store the
numbers.



//n is the number of numbers to be
swapped.



//i and j are the variables for
traversing the array.



//No other external temporary
variable is used.



while(scanf("%d",&n))



                {



                                for(i=0;i<n;i++)



                                {



                                                scanf("%d",&A[i]);



                                }



                                for(i=0;i<n;i++)



                                {



                                                for(j=i+1;j<n;j++)



                                                {



                                                                A[i]=A[i]+A[j];



                                                }



                             }



                                for(i=n-1;i>=1;i--)



                                {



                                                A[i]=A[i-1]-A[i];



                                }



                                for(i=1;i<n;i++)



                                {



                                                A[0]=A[0]-A[i];



                                }



                                for(i=0;i<n;i++)



                                {



                                                printf("%d
",A[i]);



                                }



                                printf("\n");



}



                return 0;



}


5 12 23 34 45 56
56 12 23 34 45

8 1 2 3 4 5 6 7 8
8 1 2 3 4 5 6 7

No comments:

Post a Comment