Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 779
Tsingh321 Avatar asked Feb 14 '15 19:02

Tsingh321


2 Answers

you could use a variable to increment your counter

for(int counter = 0, increment = 0; counter < 100; increment++, counter += increment){
   ...do_something...
}
like image 140
fabio.ivona Avatar answered Sep 28 '22 08:09

fabio.ivona


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...

like image 28
Kacy Avatar answered Sep 28 '22 07:09

Kacy