Infinite Loop =/ I only want it to run 5 times.

I added a while loop, with counter. But I'm not sure why it's an infinite loop. can someone modify this so I can learn what I'm doing wrong? I only want this loop to run 5 times.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
    int input = 0;
    int counter = 0;

    cout << "Enter an integer (between 1-30): ";
    cin >> input;

	while(counter != 5)	
	{    

    for(int num=0; num < input; num++)
{
       cout<<"*";
}	
	}   
}
The variable "counter" is never changed. Ever. It's always zero, and so is never 5, and the loop never exits.
you're right. Gosh it's so late and I'm blanking out.

Do I need another variable? I see num is being modified (num++) Can that be my counter variable? =/ I don't know where to stick counter++ in so it runs 5 times and the while loop can stop.

I tried sticking it in: cout<<"*" << counter++;
Bad idea.
So do you want to print "input" stars "counter" times? If so, you'll just want to increment counter once inside the while loop, but outside of the for loop. Or you can just turn the while loop into a for loop itself.
How would I turn the while loop into a for loop?

Like this?

for(int counter=1; counter++)
You are missing the second part of the for loop (the conditional).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int main()
{
    int input = 0;
    int counter = 0;

    cout << "Enter an integer (between 1-30): ";
    cin >> input;

	while(counter != 5)	
	{    

    for(int num=0; num < input; num++)
{
       cout<<"*";
}	

counter++ // you forgot this line.
	}   
}



*Smacks head*

Thanks wachtn. I wasn't aware that I could just stick the counter++ outside just like that in the open. Looked strange to me.

Here's the final output. Working. Maybe someone else might need help like I did.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int main()
{
    int input = 0;
    int counter = 0;

    cout << "Enter an integer (between 1-30): ";
    cin >> input;

	while(counter != 5)	
	{    

    for(int num=0; num < input; num++)
{
       cout<<"*";
}	

	counter++;
	cout << "Enter an integer (between 1-30): ";
    cin >> input;
	}   
}


Topic archived. No new replies allowed.