I am doing homework, but I am lost on while statements. I know this is currently if for/if, but every time I try to switch it up to while, I get confused and severely lost. I am not trying to get anyone to do my homework for me. I just want to understand how to correctly use while and do while and have it work.
the main thing to remember with while and do-while loops that is different that for loops is that they do not contain the logic that updates the test condition in them (like the x++ in your first for loop). While and do-while are usually used when the test condition is a product of the normal program flow, whereas for loops usually use conditions build specifically for use in the loop.
While and do-while are more useful when you don't know ahead of time when you will need to exit the loop. Consider a loop that reads characters from a text file. You probably won't know how big the file is, so you just keep reading until you hit it.
1 2 3 4
while( !myFile.eof() )
{
// Read the next character from the file
}
to use a while loop for the example you're using, you have to set up the condition manually outside of the loop first, and increment your test value inside the loop.
I think I understand, what you are stating and when I did the initial run with just the first while statement it came out as it was supposed too. I then set up the y statement to look like the x statement. When I debug and run it shows a single asterisk.
#include<iostream>
using namespace std;
int main()
{
int x,y;
char star = '*';
x=1;
while (x <= 11)
{
x++;
}
y=2;
while (y <= x)
{
y++;
}
{
int main()
{
int x,y;
char star = '*';
x=1;
while (x <= 11)
{
x++;
}
y=2;
while (y <= x)
{
y++;
}
{
cout << star;
}
cout << endl;
system ("pause");
return 0;
}
notice that your while( y <= x ) loop is not nested within the while( x <= 11 ) loop.
Also, your "cout << star;" line is outside of either loop, which is why it only executes once.