|
| nrose (16) | |||
im trying to write a program that will shift the values in my array one space to the left. im not sure if im going down the right path though. any help would be appreciated.
the if the values i enter are {1,3,5,7,9} it needs to output {9,1,3,5,7} | |||
Last edited on | |||
| Zhuge (634) | |
| Typeless main :( For shifting, I don't think there is an in place way to do it, so you would have to make a copy of the array with each element moved over once. | |
| kbw (1511) | |
| It's more a rotate than shift. You need to save the last value when you start (9 in this case), shuffle all the elements into the next slot up starting with the second to last. Then set the saved value into position zero. Your main's logic is correct, but syntactically incorrect. main should always return an int. | |
| pjwarez (12) | |||
| For one thing, your shiftright() function isn't even doing anything they way you have it defined. It's just iterating through the array. Also, why did you say you wanted to shift everything to the left, but you called your function shiftright() ?? You didn't say what you wanted to do with the last value, so like kdw, I'm assuming you want to throw the value of the first element onto the end. Try something like this..
| |||
Last edited on | |||
| kempofighter (669) | |
| If I were you I'd go above and beyond and make the function more generic. Write it so that the user can specify how many places to rotate or follow the example of std::rotate where you specify where you want a particular position moved to. | |
| buffbill (197) | |
| Have a look at memmove(p1,p2,n), which copies a block of memory from p2 to p1. Where n is the number of elements you want to be affected | |
| jsmith (3801) | |
| memmove is ok provided that the function only operates on arrays of POD types. | |
| buffbill (197) | |
| @jsmith....could you explain POD please. | |
| kbw (1511) | |
| http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html | |
| ramesh3076 (3) | |||
Try with the following code, it will give you the correct result what you expected.
| |||
| us3rn4m3 (14) | |
| Most complete code! I hope it helps... #include<iostream.h> #include<conio.h> void shiftright(int myarray[],int size); int main(void) { clrscr(); int myarray[] = {1, 3, 5, 7, 9}; shiftright(myarray,5); for(int i=0;i<5;i++) { cout<<myarray[i]<<' '; } getch(); return(0); } void shiftright(int myarray[],int size) { int temp; int temp1; for (int i=0; i<(size -1); i++) { temp = myarray[size-1]; myarray[size-1] = myarray[i]; myarray[i] = temp; } } | |
This topic is archived - New replies not allowed.
