Bendzukic
Bendzukic

Reputation: 35

Finding the last value of a sequence before a termination value C++

In this loop, x is incremented one too many times.

int x = 0;
while (x < 10)
{
    x = x + 3;
}
cout << x;

The output for this is 12, when i want it to be 9. Generally speaking, how would I find the last value of a sequence (in this case 9) given a restraint ( in this case 10).

Upvotes: 1

Views: 72

Answers (3)

Sanich
Sanich

Reputation: 1835

For example:

    int last = 0;
    for (int x = 0; x < 10; x+=3)
    {
        last = x;
    }
    cout << last;

or:

int x = 0;
while (x < 10)
{
    x = x + 3;
}
cout << x - 3;

or:

int x = 0;
int last = 0;
while (x < 10)
{
    last = x;
    x = x + 3;
}
cout << last;

or:

int x = 0;
while (x + 3 < 10)
{
    x = x + 3;
}
cout << x;

Upvotes: 3

BlackB0ltz
BlackB0ltz

Reputation: 49

Using your code you can try:

int x = 0;
while (x+3 < 10)
{
    x = x + 3;
}
cout << x;

Upvotes: 2

nitish-d
nitish-d

Reputation: 241

If you want to see the last value, it is better to decrease it by the same amount you are incrementing it.

int x = 0;
while (x + 3 < 10)
{
x = x + 3;
}
x = x -3;

Another way to do this is to use a break statement inside the loop with a suitable condition with which you want to leave it.

Upvotes: 1

Related Questions