Tsingh321
Tsingh321

Reputation: 91

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.

Upvotes: 9

Views: 78355

Answers (5)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14589

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 ) 
{
}

Upvotes: 0

fabio.ivona
fabio.ivona

Reputation: 618

you could use a variable to increment your counter

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

Upvotes: 8

Adan Vivero
Adan Vivero

Reputation: 422

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.

Upvotes: 0

Sumedh
Sumedh

Reputation: 404

You can try this:

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

Upvotes: 1

Kacy
Kacy

Reputation: 3430

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

Upvotes: 4

Related Questions