Basic Control Flow Continued

By this time you should be familiar with the basics behind If and Else if statements. Below you’ll see more examples and more ways to use Control Flow in your programming.

1. You’ll learn more advanced ways of manipulating control flow in your program.
2. You’ll also learn how to declare and initialize boolean variables.

Boolean Variables

Boolean variables are another built in data type in C++ that allow you to assign it either a TRUE, or FALSE value. What is this useful for? Let’s see below. (Declaring and assigning a value to a bool value is really similar to int, double, and strings).

bool success = FALSE;
int age;
cin >> age;

//If user entered a value between 0 and 120 we can assume they entered a correct value. If not, SUCCESS remains FALSE.
if ( age < 120 && age > 0 ) success = TRUE; 

//If user either put a negative number or above 120 then we "assume" they lied about their age and terminate the program.
if ( !success ) return 0; 

cout << "Based on your age we can determine..." << endl;
//Do more stuff

In other words, if the user did satisfy our age requirement, we can continue with our program.

Explanation:

You may have also noticed I used the following:

if ( !success )

This simply means if success is NOT TRUE (In other words, FALSE), the following return would execute thus terminating the program.

if ( success ) //Simple means, if SUCCESS is TRUE


If you also noticed, I included the following:

if ( age < 120 && age > 0 )


In other words, you may have more than one condition in your if statements.

You may use and or && as well as or or ||.

When you concatenate conditions with the AND operator it means in order for the if statement to execute, ALL conditions must be true. For OR only one condition must be met.

More advanced examples

Try figuring out how this following code would work. Try it yourself. It's the best way to learn! Fill in the cases of course with code of your desire.

bool success = false; //Remember to always initialize bool variables
int num1, num2, num3;

//Some lines that modify the previous variables.

if ( success ) {
	if ( (num1 <= num2) || num3 > 100 ) {
	     //Case 1
	}
	else if ( num1 == num3 ) {
	     //Case 2
	}
	else {
	     //Case 3
	}
}
else { return 0; } 

//Since success, keep doing other code.


What now?

Keep practicing! If you have any more questions feel free to ask below or join the forums and ask the community!


Related Posts

1 Star2 Stars (No Ratings Yet)

No comments yet... Be the first to leave a reply!

blog comments powered by Disqus