# Pushing values to array

**URL:** <https://forum.arduino.cc/t/pushing-values-to-array/1032561>\
**Category:** Programming\
**Created:** [September 16, 2022, 5:50pm UTC](https://forum.arduino.cc/t/pushing-values-to-array/1032561 "2022-09-16T17:50:25Z")\
**Posts on this page:** 1\
**Showing post:** 13

<div class="post-metadata">

**Author:** ![mrExplore](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/mrexplore/32/219249_2.png) [@mrExplore](https://forum.arduino.cc/u/mrExplore)\
**Post date:** [September 19, 2022, 6:54pm UTC](https://forum.arduino.cc/t/pushing-values-to-array/1032561/13 "2022-09-19T18:54:27Z")

</div>

Ok,

So I've been looking into circular buffers, an interesting and useful concept I can use in the future.  
For my current project I think I'll stick with the code I have:  
[HDD Motor Scrollwheel - working but room for improvement](https://forum.arduino.cc/t/hdd-motor-scrollwheel-working-but-room-for-improvement/1032856)]

@jfjlaros Sorry man, thanks for the help but your code is just too advanced for me at this point

I did however write code based on the circular buffer concept. It works and fits my need. I'll give implementing it into my project a thought. See the code below.

Thanks for the input to all for now, I've learned enough.

The only thing I have not figured out is what '% n' does or means. I could not google "%n" so what is that method / notation called? Thanks.

```cpp
#include <Streaming.h>

#define BUFLEN 5 // Length of buffer

int buf[BUFLEN]; // Define buffer
int writeIndex = 0; // Index at which a new value should be written to
int readFrom; // Start index of reading 
long multiplier; // Used in get() to caculate result, long so BUFLEN can be 5 or more
long result; // Returned from get()
int val; // New value to be stored 

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  val = random(1, 7);
  
  put(val);
  
  Serial << "New value has been put in: " << val << endl;

  Serial << "The values in sequence of input: " << endl;
  
  Serial << get() << endl;
  
  delay(1500);
}

void put(int item)
{
  writeIndex++; // Increment write index
  
  if(writeIndex == BUFLEN) writeIndex = 0; // Set back to zero if 'out of index' is reached
  
  buf[writeIndex] = item; // Save/store value
}

long get() // Long because return can be > 65000
{
  readFrom = writeIndex; // Start reading from the index of the last written value 
  
  multiplier = 1; // Set multiplier for the first read value
  
  result = 0; // Reset result to zero

  for(int i = 0; i < BUFLEN; i++) // Read entries of whole buffer
  {    
    result += buf[readFrom] * multiplier; // Buffer 641, result: 1*1 + 10*4 + 100*6 = 641
    
    multiplier = multiplier * 10;
    
    readFrom--; // Go backward through the buffer
    
    if(readFrom == -1) readFrom = BUFLEN - 1; // If index < 0 got to end
  }
    
  return result;
}

```

---

_[View the full topic](https://forum.arduino.cc/t/pushing-values-to-array/1032561)._
