0

I have to write code to shift all the values in the array to the right of position P, one place to the left. I can make up my own array and position P. would this code work?

for (j=6; j>1;j--)
{
x[j-1]=x[j];
}

2
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by firstPerson
0

Although inefficient I will suggest you a way.

void rot(int *a, int sz)
{
	int * t = new int[sz];

	t[0] = a[sz-1];

	for(int i = 1; i < sz; i++)
		t[i] = a[i-1];

	for(int i = 0; i < sz; i++)
		a[i] = t[i];

	delete [] t;
}
0

I am only in programming 2 for C++ i have no idea what all that means...so can you make it more simple...?

0

hmm ok lets see.

void rot(int a[], int sz)
{
   const int MY_MAX = 100; // assumes the array passed size is < 100
int  temp[MY_MAX];

	temp[0] = a[sz-1]; //copy last element from the array thats passed to the first element

	for(int i = 1; i < sz; i++ )  //now copy every element except the last 1 
		temp[i] = a[i-1];

	for(int i = 0; i < sz; i++) //now temp contains the rotated array so copy it back to the array
		a[i] = temp[i];
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.