C++ Countdown and Count-up Loop

Hello,

I am new to C++ programming, and I am trying to create a program that counts up, and then counts down like this:

70,80,90,100,90,80,70

I want to make two loops. Currently, my code looks like this, but it is not working:

#include <iostream>

int main(int argc, const char * argv[]) {
// create loop to count up from 70, 80, 90, 100
int i;
int p;

for (i = 70; i <=70; i+=10) {
std::cout << i << std::endl;
}

//create second loop to count down from 90,80,70
for(p= 90; p <=90; p -= 10) {
std::cout << p << std::endl;
}

return 0;
}

Can you help me identify where I am wrong and how I can fix these two loops?
Thank you!
Last edited on
A for loop can be converted to a while loop:
1
2
3
4
5
6
7
8
9
10
11
12
for ( i = 70; i <=70; i+=10 ) {
  std::cout << i << std::endl;
}

==>

i = 70; // the initial state
while ( i <= 70 ) // condition
{
  std::cout << i << std::endl;
  i += 10; // increment
}

On first time the i==70 creates a condition: 70<=70, which is true.
Therefore, the loop body is executed and "70" prints out.
At the end of this iteration, you increment i by 10, and therefore i==80.

Now we test the condition for second time. 80<=70 is not true and thus the loop is over. What kind of condition would be true as long as i is not greater than 100?


The other loop.
On first time 90<=90, which is true. Then you decrease p by 10.
On the second time 80<=90 is true.
On the third time 70<=90 is true.
The p decreases every time.
How small must a number become so that it would no longer be smaller than 90?
Perhaps the loop should continue as long as the p is larger than something?
U can use the code as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main(int argc, const char * argv[]) {
	// create loop to count up from 70, 80, 90, 100
	int i;
	int p;

	for (i = 70; i <= 100; i+=10) {
		std::cout << i << std::endl;
	}

	//create second loop to count down from 90,80,70
	for(p= 90; p >= 70; p -= 10) {
		std::cout << p << std::endl;
	}

	//system("Pause");
	return 0;
}
Topic archived. No new replies allowed.