473,413 Members | 2,051 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

irregular (non-consecutive) iteration (for loop)

hi there,

suppose I want to iterate for a specific variable e.g. i , but for non
regular (or consecutive) values. For example i=0,1,2,4,5,7,8 etc
how can I do that with a for loop?

MY solution which is not that elegant involves if statements (or switch
statements) in the body of the loop: e.g.
for (int i=0; i<=8; i++)
{
if ((i!=3) && (i!=6))
{
// execute whatever
}

//else do nothing

}
is there a more elegant/compact/precise way of doing the above?

Thank you
** Posted from http://www.teranews.com **
Jul 10 '08 #1
6 2996
Nobody wrote:
hi there,

suppose I want to iterate for a specific variable e.g. i , but for non
regular (or consecutive) values. For example i=0,1,2,4,5,7,8 etc
how can I do that with a for loop?

MY solution which is not that elegant involves if statements (or switch
statements) in the body of the loop: e.g.
for (int i=0; i<=8; i++)
{
if ((i!=3) && (i!=6))
{
// execute whatever
}

//else do nothing

}
is there a more elegant/compact/precise way of doing the above?
const int nums[] = {0,1,2,4,5,7,8};

for (int in = 0; in < NumElem(nums); ++ in ) {
int i = nums[in];
}
Jul 10 '08 #2
Sam
Nobody writes:
hi there,

suppose I want to iterate for a specific variable e.g. i , but for non
regular (or consecutive) values. For example i=0,1,2,4,5,7,8 etc
how can I do that with a for loop?

MY solution which is not that elegant involves if statements (or switch
statements) in the body of the loop: e.g.
for (int i=0; i<=8; i++)
{
if ((i!=3) && (i!=6))
{
// execute whatever
}

//else do nothing

}
is there a more elegant/compact/precise way of doing the above?
It's just a matter of thinking logically:

static const int loop_iter[]={0,1,2,4,5,7,8};

int ii;

for (ii=0; ii<sizeof(loop_iter)/sizeof(loop_iter[0]); ++ii)
{
int i=loop_iter[ii];

// Now, do whatever you want with "i"
}
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEABECAAYFAkh1fEcACgkQx9p3GYHlUOKMqQCbBeWCYEMFik rz6CMyJdjTjh9K
7wkAnjoRqzDwcupq5wT5VOIfs3A8MsWs
=+Xw1
-----END PGP SIGNATURE-----

Jul 10 '08 #3
Nobody wrote:
suppose I want to iterate for a specific variable e.g. i , but for non
regular (or consecutive) values. For example i=0,1,2,4,5,7,8 etc
how can I do that with a for loop?
MY solution which is not that elegant involves if statements (or switch
statements) in the body of the loop: e.g.
is there a more elegant/compact/precise way of doing the above?
You could overload all necessary operators of a "Range" class
that has an underlying vector (or sth. else). If so, you might
write:
int main()
{
int irregular[] = {1,2,2,2,5};
Range i(irregular, 5); // <== that's our class

for(i=0; i<5; i++) // looks ok ...
cout << i << endl;

return 0;
}
This would indeed show the sequence given in the
int array 'irregular'.

How would such a range class look like? Simple, just
inherit from a std::vector and add the overloads:

class Range : public vector<int>{
int pos;
public: Range(int a[], int n) : vector<int>(a, a+n), pos(0) {}
int operator ++ (int) { return operator[](pos++); }
int operator = (int v) { return pos = v; }
int operator < (int b) { return pos < b; }
int operator () () const { return operator[](pos); }
operator int() const { return operator[](pos); }
};
Of course, to get that working you'll
need the headers:

#include <vector>
#include <iostream>

and you would add here:

using namespace std;

before the class definition.

Regards

Mirco
Jul 10 '08 #4
In article <f1******************@news.teranews.com>, no****@nowhere.com
says...
hi there,

suppose I want to iterate for a specific variable e.g. i , but for non
regular (or consecutive) values. For example i=0,1,2,4,5,7,8 etc
how can I do that with a for loop?

MY solution which is not that elegant involves if statements (or switch
statements) in the body of the loop: e.g.
for (int i=0; i<=8; i++)
I'd probably do something like this:

int f(int i) {
if (i==3 || i==6)
return i+2;
return i+1;
}

for (int i=0; i<max; i=f(i))
// whatever

of course, I've only defined f to do exactly what you showed, skipping 3
and 6, but nothing else. If you really meant (for example) to skip all
multiples of three, that's somewhat simpler. In any case, it's purely a
matter of figuring out what you want and writing 'f' to suit.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 10 '08 #5
Sam wrote:
[..]
It's just a matter of thinking logically:

static const int loop_iter[]={0,1,2,4,5,7,8};

int ii;

for (ii=0; ii<sizeof(loop_iter)/sizeof(loop_iter[0]); ++ii)
{
int i=loop_iter[ii];

// Now, do whatever you want with "i"
}
And, logically speaking/thinking, why is 'ii' declared outside of the
'for' loop? :-)

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 10 '08 #6
On Jul 10, 3:55 pm, Jerry Coffin <jcof...@taeus.comwrote:
In article <f1468$48722d2a$20...@news.teranews.com>,
nob...@nowhere.com says...
suppose I want to iterate for a specific variable e.g. i ,
but for non regular (or consecutive) values. For example
i=0,1,2,4,5,7,8 etc how can I do that with a for loop?
MY solution which is not that elegant involves if statements
(or switch statements) in the body of the loop: e.g.
for (int i=0; i<=8; i++)
I'd probably do something like this:
int f(int i) {
if (i==3 || i==6)
return i+2;
return i+1;
}
for (int i=0; i<max; i=f(i))
// whatever
Which could easily be written without the function:

for ( int i = 0 ; i < max ; i += (i == 3 || i == 6 ? 2 : 1))

(Whether that's an improvement is another question. Written on
a single like, like above, it's actually rather intimidating,
but correctly formatted:

for ( int i = 0 ;
i < max ;
i += (i == 3 || i == 6
? 2
: 1) )

it's not that bad.)
of course, I've only defined f to do exactly what you showed,
skipping 3 and 6, but nothing else. If you really meant (for
example) to skip all multiples of three, that's somewhat
simpler. In any case, it's purely a matter of figuring out
what you want and writing 'f' to suit.
More generally, in C++, he as two choices:

for ( int i = 0 ; i < max ; ++ i ) {
// use f(i) throughout the loop...
}

or

for ( int i = 0 ; i < max ; i = f(i) ) {
// use i throughout the loop...
}

Most other languages (or at least older languages) only offer
the first.

And of course, in the above, f(i) should be understood as any
arbitrary expression taking an i, and returning the same type.
Array[i], for example (so the previous suggestions fall into the
first pattern).

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jul 11 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Steven Bethard | last post by:
Can someone point me to the documentation on what's supposed to happen when you use the "for x in X:" syntax when X does not have an __iter__ method? I know that the code: >>> class S: .... ...
6
by: Shill | last post by:
I have several questions. In C, AFAIU, a for loop is just syntactic sugar for a while loop. for (i1; i2; i3) i4; is equivalent to i1 while (i2) {
7
by: Mahesh Kumar Reddy.R | last post by:
Hi Can any body resolve this.. In what cases one of the loop constructs better than other interms of speed , space and any other (redability). thanks mahesh
3
by: Ben R. | last post by:
In an article I was reading (http://www.ftponline.com/vsm/2005_06/magazine/columns/desktopdeveloper/), I read the following: "The ending condition of a VB.NET for loop is evaluated only once,...
23
by: Mitchell Vincent | last post by:
Is there any way to "skip" iterations in a for loop? Example : for x = 1 to 10 if something = 1 next endif
8
by: Jim Langston | last post by:
There's the thing about iterating though a map or vector when you may delete one of the elements, where you simply assign the iterator to the map.erase() statement or increment it if you don't. ...
12
by: poornimamprabhu | last post by:
Hi there, suppose i have piece of code like main() { int i,j; for(i=0;i<10;i++){ int k = i; printf("%d %p = *%d\n",i,&k,k); }
7
by: jmDesktop | last post by:
From the Python.org tutorial: .... for x in range(2, n): .... if n % x == 0: .... print n, 'equals', x, '*', n/x .... break .... else: .... #...
5
by: Dave Elfers | last post by:
Hello, I am using a for loop to iterate through an array and need to assign each iteration to a new variable, such as arr = for i in arr: print i but instead of printing i, I want...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.