Tuesday, November 15, 2016

Getting good at: C++ | #8 - while and do-while loops

8 - inception

Hey guys. The next pewdiepie here. Today, I'm going to show you how to make 'while' and 'do-while' loops. So a while loop is a type of loop that occurs when a conditional is true. If we make a variable named 'conditi0nal', and set it equal to 100, then we can write something like:

while(conditi0nal<=200)
{
     cout << "memes" << endl;
     conditi0nal++;
}

So as long as 'conditi0nal' is less than or equal to 200, it will print out "memes" and increase the value of 'conditi0nal' by one until it reaches 200.

A do-while loop is similar to the while loop, except that it does that body of code regardless if the conditional is true or false. So something like this:

do{
     cout << "memes" << endl;
     conditi0nal++;
}while(conditi0nal<=200);

This version of the while loop isn't used very often, so you don't have to worry about it too much.

While loops can also be used for user-defined variables. For example:

int answer;
cout >> "Is Control Alt Defeat best YouTuber?\n1. Yes\n2. No\n";
cin >> input;

while (input!=1)
{
     cout << "wrong answer" << endl;
     cin >> input;
}

cout << "thats right" << endl;

So in this program, we created a variable, and made the user input a value of 1 or 2. If the variable is set to 1 (it better not be), it will keep going until you set it to 2, in which case it will end the program.

That's all for now. 

No comments:

Post a Comment