Lab: If Statement
Lab: If Statement
If Statement
int x = 5;
if (x < 10) {
cout << "Less than 10" << endl;
}
Code Visualizer
If the boolean expression is false, the code in curly braces is skipped, and
the program continues as normal.
int x = 20;
if (x < 10) {
cout << "Less than 10" << endl;
}
cout << "And the program continues...";
Code Visualizer
if (age < 20) { if ((age < 20) && (age > 10)) {
if (age > 10) { cout << "Teenager";
cout << "Teenager"; }
}
Code Visualizer
Lab: If Else Statement
int x = 10;
if (x > 50) {
cout << to_string(x) + " is greater than 50" << endl;
}
else {
cout << to_string(x) + " is less than 50" << endl;
}
Code Visualizer
The if part of the if else statement is written as before. The else keyword
is not indented; it should be aligned with the if keyword. else is followed
by an open curly brace {. You do not use a boolean expression with else.
All code that should run when the boolean expression is false should go
before the closing curly brace }.
int x = 50;
if (x > 50) {
cout << to_string(x) + " is greater than 50" << endl;
}
else {
cout << to_string(x) + " is less than 50" << endl;
}
Code Visualizer
The output of the program does not make sense. 50 is not less than 50.
Sometimes using <= and >= need to be used. Another solution is to update
the output to be more inclusive such as replacing is less than 50 with is
less than or equal to 50. In either case, be sure to think through all of
the possible outcomes, and make sure your code can function properly in
all of those scenarios.
Lab: Switch Statement
int size = 3;
switch (size) {
case 1: cout << "Short"; break;
case 2: cout << "Tall"; break;
case 3: cout << "Grande"; break;
case 4: cout << "Venti"; break;
case 5: cout << "Trenta"; break;
default: cout << "Grande";
}
Code Visualizer
Remember to include break; statements at the end of each case. Check out
what happens when you remove them.
int size = 3;
switch (size) {
case 1: cout << "Short";
case 2: cout << "Tall";
case 3: cout << "Grande";
case 4: cout << "Venti";
case 5: cout << "Trenta";
default: cout << "Grande";
}
Code Visualizer
The output of the program does not make sense because the program
continues through all of the cases after the initial case is matched to a
value. In the example above, the program prints the command for case 3
as well as all of the commands that follow.
Lab Challenge: Month of the Year
Conditionals Challenge
Write a program that determines the month of the year based on the value
of a variable called month. The variable will be a number from 1 to 12 (1 is
January, 2 is February, etc.). Use a cout << statement to write the month to
the screen.