CPP If-Statement
CPP If-Statement
If Statement Syntax
Conditionals are pieces of code that make a decision about what the
program is going to do next. The most common conditional is the if
statement.
.guides/img/IfSyntax
It is best practice to also indent the lines of code inside the curly braces to
visually differentiate them from the commands that will always run.
Copy the code below into the text editor on the left and then click the TRY
IT button to see the output. You can also click on the ++Code Visualizer++
link below to see how the program runs behind-the-scenes. If the visualizer
does not open properly after a few seconds, click the Refresh code code
button at the top to restart it.
if (5 > 4) {
cout << "I print 1st if true" << endl;
cout << "I print 2nd if true" << endl;
}
cout << "I will always print" << endl;
Code Visualizer
If Statement
If Statement
if statements test to see if a certain condition is true. If yes, then specific
commands are run. The simple if statement does not do anything if the
boolean expression is false.
if (7 != 10) {
cout << "The above statement is true" << endl;
cout << "The above statement is still true" << endl;
}
cout << "This is not related to the if statement" << endl;
Code Visualizer
challenge
Code Visualizer
Code Visualizer
challenge
Code Visualizer
Compound Conditional Statements
challenge
.guides/img/CompoundConditional
The code on the left is a nested if statement - which means an if
statement is inside another if statement.
The code with the compound conditional (on the right) has fewer lines of
code, and is easier for a human to read. In fact, it almost reads like a
sentence.
Formative Assessment 1
Formative Assessment 2