< Browse > Home / C++ / Blog article: Basic Control Flow

Basic Control Flow

June 24th, 2008 | No Comments | Posted in C++ by Diego

In the following tutorial, you’ll learn how to use if, and if-else statements. They are useful for deciding on what lines of code to execute based on values of previous variables in your program.


The If Statement

An example is as follows

int x;
if ( condition ) x = 50; //If condition returns TRUE, assign 50 to X.
 

In other words, if the condition you provide returns a boolean value ( is a value that returns either TRUE or FALSE ) TRUE, then the following statements enclosed with {}’s are executed (no need if only one statement follows the if statement).


You may use the following operands in your conditions…
== – EQUAL TO
!= – NOT EQUAL TO
< - LESS THAN
<= - LESS THAN OR EQUAL TO
> – GREATER THAN
>= – GREATER THAN OR EQUAL TO

Here is an actual example.

int number;
cin >> number;
if ( number == 50 ) {
cout << "Congratulations! You picked the right number!" << endl;
}
 

In other words, if the user typed in 50, the if statement will be true and print the following line to the screen.

The If and Else

Let’s say we want to output something if it was false.

int number;
cin >> number;
if ( number == 50 ) {
cout << "Congratulations! You picked the right number!" << endl;
}
else {
cout << "Sorry! You were wrong!" << endl; //Second Statement
}

Then, if the user didn’t type in 50, it would output the second statement.

The If, Else-If, and Else

What if we wanted to check other conditions as well?

int number;
cin >> number;
if ( number == 50 ) {
cout << "Congratulations! You picked the right number!" << endl;
}
else if ( number > 50 ) {
cout << "Sorry! You were over!" << endl; //New Statement
}
else {
cout << "Sorry! You were way off!" << endl;
}

In other words, this one has a different output if the user entered a number larger than 50! If the user didn’t choose 50, or a number larger than fifty, then the last else statement would be executed.


Keep in mind that you may add multiple else if statements! Just remember to have good coding style in order for any future reader to understand what statements pertain to what if condition. The way my code is written is a really good way of styling your code as its easy to read and follow!

So what now?

If you have trouble don’t be afraid to post below any questions, comments, or concerns!

In the next tutorial expect to learn how to use If, Else If, and Else statements in more detail!



Leave a Reply |
Tags: , , ,

Related Posts to Basic Control Flow

Leave a Reply