C++ Programming Series: Using Conditional Statements (Part 4)

In the last few previous posts, we learned some of the conditional statements, user input and basic arithmetic. Now, time to use some bits of all of them in one place!

Just like if-statements, there is another conditional statement called as while-statement. Below is a very simple example of this:

while(true)
{
  cout << "Looping..." << endl;
}

When you run this code, you might be wandering that why the program is not stopping? Well, it’s because it is an infinite loop. After the while keyword, there is a condition just like that of if-statement. The code in the braces, will keep repeating itself while the condition after the while is true. Ofcourse, you got the meaning! It is just like a recurring if-statement.

We can do some interesting things with it like this:

int loopCounter = 0;
while(loopCounter < 10)
{
  cout << "Looping " << ++loopCounter << endl;
}

When we run this code, we see that the word “Looping” along with a increasing number, is printed 10 times. The increasing number starts to print from a value, 1. It will start from a value, 0, with postfix increment operator(loopCounter++). We can also do loopCounter = loopCounter + 1; or loopCounter += 1; at the end or start of the braces of while-statement.

Can you think of some program that uses while-statement along with getline(user input)? Password input! Check out the code below:

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string password = "kabrakadabra";
  string entry = "NULL";

  while(entry != password)
  {
    cout << "Enter your password: ";
    getline(cin, entry);
  }

  cout << "Correct password!" << endl;

  return 0;
}

What if we want to say wrong password each time it is entered wrong! Then, below the getline, we can add:

if(entry != password)
{
  cout << "Wrong password! Please try again!" << endl;
}

Don’t you think that it’s perfect? Woohoo! we are going to be true programmers in the future, don’t we? Yes, but only if you do few experiments with it as a home task!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s