run through array from posx

May 19, 2014 at 3:03pm
Hello, can i easily run through all positions of an array, when i start
at pos x (somewhere in middle), so when i reach the end i continues at pos0?

I already solved that but with a temp variable, setting max length of the loop back to posx and loop counter to 0. is there a better way?
May 19, 2014 at 3:17pm
Why do you need something so specific?
There might be better way.

If not: two for loops is usual way to do that.
May 19, 2014 at 3:26pm
because my program starts searching in an array at a certain position, but needs to check each position in the array once.
2 for loops? you mean first one goes from start position to end of array
and secong one goes from 0 to start position?

that sounds even worse for runtime? :/
May 19, 2014 at 3:29pm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include <iostream>
using namespace std;

void showArray(char[], int, int);

int main()
{

	char myarray[] = "C++ Programming-";

	showArray(myarray, 16, 3);
	return 0;

}

void showArray(char array[], int size, int offset)
{
	int count = 0, index = offset;
	do {
		cout << array[index];
		count++;
		index++;
		if (index == size)
			index = 0;
	} while (count < size);

}
 Programming-C++
May 19, 2014 at 3:30pm
that sounds even worse for runtime? :/
Why? Both ways iterates over same amount of items. Solution with two loops is more likely to hit CPU data prefetch and actually work faster.

Softrix solution will work nicely on any modern CPU too.
Last edited on May 19, 2014 at 3:31pm
May 19, 2014 at 3:32pm
thx softrix i will try that one.
Topic archived. No new replies allowed.