I'm writing some while loops but I feel like there is a better way to write them.

``````int i=3;
while (i<31)
{
cout << i << " ";
i+=3;
} //this one is for the first 10 terms of a sequence starting with 3 and adding 3 each time.

int i=2;
while (i<50000)
{
cout << i << " ";
i*=2;
} //this one is the first 15 terms starting at 2 and doubling each one.``````

Is there some way to let the program know how many variables to show without figuring out how far it has to go? Also, what if I wanted to write a loop where each number is subtracted by one more than the one before it (100, 99, 97, 94, 90...)?

Is it a requirement that you use a "while" loop?
Yes, there is a way to pre-determine the number of loops, but it's not more efficient.

Also, what if I wanted to write a loop where each number is subtracted by one more than the one before it (100, 99, 97, 94, 90...)?

use a counter that increments itself, then you use this counter to subtract the main variable

## All 5 Replies

Is it a requirement that you use a "while" loop?
Yes, there is a way to pre-determine the number of loops, but it's not more efficient.

Also, what if I wanted to write a loop where each number is subtracted by one more than the one before it (100, 99, 97, 94, 90...)?

use a counter that increments itself, then you use this counter to subtract the main variable

Is it a requirement that you use a "while" loop?
Yes, there is a way to pre-determine the number of loops, but it's not more efficient.

while loop is the requirement.

use a counter that increments itself, then you use this counter to subtract the main variable

I tried something like this:

``````int i=100, j=0;
while (i>50)
{
cout << i-j << " ";
j++;
i--;
}``````

but it's just decreasing by 2 all the way to 0.

don't decrement the value of i by 1 every time you only need to use j n the operation...
something like this:

``````while (i>50)
{
cout << i << " ";
j++;
i-=j;
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.