FOR LOOPS AND DOUBLING MY COUNTER

Hey guys so i am doing a program for my programming fundamentals class and i stumbled upon a question i cant quite get.

QUESTION:

Write a for loop that starts at 1 and ends when it goes over 1000. The body of the loop should double the counter during each iteration. Print the iteration number along with the value of the counter.
OUTPUT: Loop iteration # and the value of counter
Loop iteration: 1 Counter = 1
Loop iteration: 2 Counter = 2
Loop iteration: 3 Counter = 4
Loop iteration: 4 Counter = 8
Loop iteration: 5 Counter = 16


Now i have began the code where i can print out the correct order of the loop iteration but cannot get my counter to double itself after every iteration. Any ideas on how to do this?


[CODE BELOW]

1
2
3
4
5
6
7
8
9
10
11
12
13
  int loopDoubleCount()
{
	const int MIN_NUM = 1, MAX_NUM = 1000;
	int x, count = 0;

	for (x = MIN_NUM; x <= MAX_NUM; x++)
	{
		
	cout <<"Loop iteration: " << x << " Counter= " << count << endl;

	}
	return 0;
}
Try x *= 2 instead of x++
To increment the counter by current value you need counter += counter;
See comments in the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
int loopDoubleCount()
{
	const int MIN_NUM = 1, MAX_NUM = 1000;
	int x, count = 1; // count must start as positive value

	for (x = MIN_NUM; x <= MAX_NUM; x++, count += count) // note += for count
	{
		
	cout <<"Loop iteration: " << x << " Counter= " << count << endl;

	}
	return 0;
}
Last edited on
Topic archived. No new replies allowed.