What looping am i going to use?

Oct 5, 2011 at 7:30am
Hello.. I'ts hard for me to this. I don't know what kind of looping am i going to use.

Make and run a program that will ask a password, the program will not stop asking until you enter the correct password.
Oct 5, 2011 at 8:05am
A while loop will work here, here's how I would do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;
int main ()
{
     string Input = "";
     while (1)
     {
           cout << "Enter password:  ";
           cin >> Input;
           if (Input == "password") break;
           else cout << endl << endl;
     }
     return 0;
}
Oct 5, 2011 at 8:36am
There are only two kinds of loops: while and for. Both can be used for all purposes, but in general, a for loop is for a pre-determined amount of iterations (e.g. until i = 10, until i = array.size(), etc.) and a while loop is for conditional iterations.

A simple example:
For some reason, you're going to be holding your breath. There are two options:
-Hold your breath for 10 seconds.
-Hold your breath until you no longer can.

The first would be a for loop (it's going to be 10 seconds, no matter what happens) and the second is a while loop ('until you no longer can' could be 5 seconds or could be 50 seconds, depending on your ability and the moment).
Oct 5, 2011 at 9:58am
You forgot the do while loop, unless you meant to leave it out?
Oct 9, 2011 at 10:59am
Thank's for the information.
Oct 9, 2011 at 3:20pm
do while is pretty much the same as a while with the exception that a while can skip the first iteration if something prior doesn't work out right.

A while will work in any instance that a do while will work and I think any performance gained to go with the added complexity is absolutely negligible (you perform the conditional one fewer times). I never use the do while.
Topic archived. No new replies allowed.