Loop need a better understanding

Can someone explain loops to me a little better. I am studying loops and watching youtube videos and i just cant understand the loops. I picked up everything else really fast its just the loops. Can someone help explain it to me please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

For example:

#include <string>
#include <iostream>
using namespace std;
int main ()
{
string password;
do
{
cout << "Please enter your password: ";
cin >> password;
} 
while ( password != "foobar" );
cout << "Welcome, you got the password right";
}

Why is it: while ( password != "foobar" );
shouldnt it be == why would the != mean that foobar is the password. != means not equal to. So what the heck?
Its something like this: password!=foobar, then read password from input again

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <iostream>
using namespace std;
int main ()
{
string password;
do
{
cout << "Please enter your password: ";
cin >> password; //the execution will remain in this block
                             //WHILE password!=foobar
} 
while ( password != "foobar" );

//as soon as password=foobar it will exit the while loop
cout << "Welcome, you got the password right";
}
Last edited on
The do/while idiom says you want to execute the contents of the loop at least once and that you want to continue executing the loop while the condition is true.

In your situation, you want to continue executing until password == foobar. So you have to think about this in the negative. If the password is not foobar, then you want to execute the loop again prompting the user to input a new password. When the password is correct, the while != condition will be false and control will pass to the statement after you loop.

Some languages have a do/until (cond is true) construct, which IMO makes more sense. If you find it easier to think about your loop as a do/until, it's easy to convert it to a do/while simply by inverting the condition.

Last edited on
Topic archived. No new replies allowed.