• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array Question.  RSS feed

 
David Laverdy
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im writing a method to rotate the numbers in a array given a specified number.


What I'm finding is the loop works once, than after that the loop seems to fail, and I can't figure out why. It's failing in the way that the temp variable is assigned correctly the first 2 times the loop is initiated, than the temp variable stays the same. I hope this is enough information to nudge me along. Thanks for all the help in advance!
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sevral points in no particular order:

- You're rotating the first "numberOfPositions+1" elements, not the first "numberOfPositions" elements; is that what you want to do?

- Assuming that the first element should go into the (numberOfPositions+1)-th spot, line 9 is incorrect. Not sure what "nElems" is, but you probably meant to use "numberOfPositions" instead.

- you should move the assignment of the "temp" variable out of the loop - it gets assigned the value of the 0-th element, but should not change afterwards. (At least if I understand the intent of this code correctly.)
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The logic in your program has some flaws. The best way to see how it works is to take a pencil and paper and draw it out. For example, assuming a[] is [1,2,3,4,5], and the nElems variable has the array length (5), the first loop would look like this:

The number in parenthesis is the value of the variable after assignment. So after line 3 is executed, temp has a value of 1. If you do this, you should see how the flow goes, and why you get the behavior you do. I would then do the reverse to fix the problem: draw the sequence that does what you want to happen using pencil and paper. Then translate that sequence into code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!