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.

Edited 4 Years Ago by thines01: n/a

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;
	}
This question has already been answered. Start a new discussion instead.