I'm trying to make a program where people enter how many lines they want and the loop will print that many, what I have so far is: #include <iostream.h>
#include <windows.h>
int main()
{
int count = 0;
int lines;
cout<<"Enter a number to display that many lines"<<endl;
cin>> lines;
do
{
count++;
cout<<endl;
cout<<"test";
}while(count = lines);
system("PAUSE");
return 0;
}
but it is looping indeffinatly, thanks for any help!
you will always get an infinite loop with that program, I actually did same exact same thing when I first started learning c++. In you while statement you have "count = lines". The operator "=" sets the value of a variable to another. So the condition you set in the while statement reads "count takes the value of lines", since that is always true you have an infinite loop. To check if one var. is the same as another do this "count == lines" which checks if count is the same as lines but doesn't change it's value, however in your program this isn't going to work, I'll let you see if you can figure out why.
Thinking about it it would also be better to use a while loop or a for loop, not a do...while loop, the do...while will output a line even if the user enters 0 as input.
Yea my teacher taught us to use a while loop for when you did not know how many times to loop around for ex in game a while loop might be used to keep checking if you are still alive etc. But the for loop should be used when you know how many times to loop, and in this case you do know, the user tells you when he inputs lines.
Death in games are normally event driven >.>. The for loop can be used in many ways. In an emulator, it's often used with for(;;) for infinite and optimized looping. while(1) isn't used because most compilers check to see if 0 is true or false which loses obvious wasteful CPU. In these cases, it shouldn't matter since in the end the opcodes given should be the same (I've been trying to find the documentation to back this up unsuccessfuly).
Though often or not, the for loop is standard when an incrementing index variable is needed. The while loop is common for having a variable checked for true or false before code is execute and the do until loop is used when your code needs to be executed at least once before the given boolean is checked.
For while(1) (I assume you meant 1, not 0), the compiler should automatically change it into true, then realize that it is a constant, so there should be no difference.