Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a bunch of variables named index1, index2, ..., indexn. I want to calculate i = array[index1] + array[index2] + ... + array[indexn]. I heard that I can do that in a loop, getting the current variable name from the loop index. How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
404 views
Welcome To Ask or Share your Answers For Others

1 Answer

Instead of having individual variables like this:

int index1, index2, index3, ...indexN:

you should consider using an array of indices:

int index[N];

and then you can sum in a loop, e.g.

sum = 0;
for (i = 0; i < N; ++i)
{
    sum += array[index[i]];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...