简体   繁体   中英

C++ How do I increase For Loop Increments

I want to increase the increment by 1 each time. I want to be able to get 1, 3, 6, 10, 15, 21, 28, 36, 46...

First it adds 1 then 2 then 3 then 4 and so on and so fourth.

you could use a variable to increment your counter

for(int counter = 0, increment = 0; counter < 100; increment++, counter += increment){
   ...do_something...
}

You can try this:

int value=0;
for(int i=1;i<limit;i++){
    value+=i;
    System.out.println(value);
}
int incrementer = 1;
for ( int i = 1; i < someLength; i += incrementer )
{
    cout << i << endl;
    ++incrementer;
}

or if you want to do it in as few lines as possible (but less readable):

for ( int i = 1, inc = 1; i < 100; ++inc, i += inc )
      cout << i << endl;

Output:

1

3

6

10

etc...

I'm assuming that you want the number 45 instead of 46. Therefore I'd say we could use a for loop for this one.

int x = 0; 
int y = 1;

for(int i = 0; i <= 9; i++)
{
    x += y;
    cout << x << ", ";
    y++;
}

I stopped at 9 since that's what you used up ahead as the last number. Obviously we can go on longer.

Your question offers one sequence, but incorrect hypotesis.

1, 3, 6, 10, 15, 21, 28, 36, 46 - increment here is 2,3,4,5,6,7,8,10. 10? Should the last value be equal to 45?

In general loop would look like:

const unsigned begin_count = 1;
const unsigned begin_increment = 2;
for(unsigned count = begin_count, incr = begin_increment; condition; count += incr, ++incr) 
{
}

Where condition is some kind of expression which must be true as long the loop's body to be executed.

Let say, that's actually right and perhaps 46 is the end of array you never want to miss. Or 8 is increment at which you want to stop add one and start add 2, then condition should be designed accordingly. You actually can do increment inside of condition if it required to be done before the body loop is executed! The comma in for() expressions are sequence operators and ternary operator is allowed ( Function call, comma and conditional operators ). Note, the first "parameter" of for() loop isn't an expression, it's a statement, and meaning of comma there depends on the nature of statement. In this particular case it's a declaration of two variables.

At that stage when for() becomes too complex, for readability one should consider use of while or do while loops.

constexpr unsigned begin_count = 1; 
constexpr unsigned begin_increment = 2; 
constexpr unsigned end_count = 46;  // 45 + 1
for(unsigned count = begin_count, incr = begin_increment; 
    count < end_count;
    count += incr, ++incr ) 
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM