0% found this document useful (0 votes)
33 views

C++ 4. Conditional Statements

The document discusses different types of conditional statements in programming including if, if else, and if else if else statements. It provides examples of the syntax and flow for each statement type and how they work based on different conditions being true or false.

Uploaded by

Thomas Graham
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

C++ 4. Conditional Statements

The document discusses different types of conditional statements in programming including if, if else, and if else if else statements. It provides examples of the syntax and flow for each statement type and how they work based on different conditions being true or false.

Uploaded by

Thomas Graham
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Bachelor of Information Technology

PRG1002 - Programming I

Conditional
Statements

Control the flow with selectors


● if statement
Contents
● if...else statement

● if...else if...else statement

● switch statement

● Nested conditions

● Ternary operator
Recap - Relational operators

● The conditions tested are specified using comparison operators. Conditions are expressions that
evaluate to a boolean value - a true or false value. The following comparison operators are
available:

○ Equality: The operator ‘==’ returns true if left operand is equal to right operand

○ Inequality: The operator ‘!=’ returns true if left operand is not equal to right operand

○ Greater-than: The operator ‘>’ returns true if left operand is greater than right operand

○ Lesser-than: The operator ‘<’ returns true if left operand is lesser than right operand

○ Greater-than or equal-to: The operator ‘>=’ returns true if left operand is greater than or equal to right operand

○ Lesser-than or equal to: The operator ‘<=’ returns true if left operand is lesser than or equal to right operand
Recap - Logical operators

● Logical operators are used to combine two or more conditions. The result of a logical operator is a
boolean value either true or false. They are described below:

○ Logical AND: The operator ‘&&’ operator returns true when both the conditions are satisfied. Otherwise it
returns false.

○ Logical OR: The operator ‘||’ operator returns true when one (or both) of the conditions is satisfied. Otherwise it
returns false if both the conditions are not satisfied.

○ Logical NOT: The operator ‘!’ operator returns true if the condition is not satisfied, returns false if the condition
is satisfied.
The truth tables

● Truth tables show the result of combining any two boolean expressions using AND, OR or NOT
operator.

Condition 1 (x) Condition 2 (y) x && y x || y !(x || y)

false false false false true

false true false true false

true false false true false

true true true true false


if statement

● Programs often take actions based on conditions, only executing particular statements when some
condition is true.

● The if statement selects and executes one or more statements based on some condition.

● If the condition is true, then the statements in the if block are executed.

● If the condition evaluates to false then the statements are skipped and the program control passes
to the statement following the if statement.

● Example:
if (age >= 18)
{
cout << “You may enter!\n”;
}
Syntax - if statement

if (condition(s))
{
statement1;
statement2;
statement3;
}

● If the condition evaluates to true, then the block of code inside the if statement will be executed.

● If the condition evaluates to false, then the block of code inside the if statement is skipped and
the first set of code after the end of the if statement (after closing curly brackets) will be executed.

● Conditions can be combined with logical operators


Flowchart of if statement

true
condition

statements
false inside if

statements after
if
How if statements work?
int num = 0;
cin >> num; // -2

if (num < 0) ● The variable num is retrieved and compared


{ against 0.
cout << num << "is not a positive value\n";
}
// statements after if ● If the variable num is less than 0, then the
cout << "This statement is always executed\n"; cout statement is executed, and exits the if
statement and executes the cout statement
int num = 0;
after the closed curly brackets
cin >> num; // 6

if (num < 0) ● If the variable num is greater than 0, then the


{
cout statement inside if is skipped, and
cout << num << "is not a positive value\n";
} executes cout statement after the closed
// statements after if curly brackets.
cout << "This statement is always executed\n";
if...else statement

● Depending on the outcome of the condition, the if...else statement causes one of the two possible
statement(s) to execute.

● An if statement can be followed by an optional else statement, which executes when the condition
is false.

● If the condition evaluates to true, the statement(s) inside the body of if is executed.

● If the condition evaluates to false, the statement(s) inside the body of else is executed.

● Example: if (age >= 18)


{
cout << “You may enter!\n”;
}
else
{
cout << “You are not old enough.\n”;
}
Syntax - if...else statement
if (condition)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}

● If the condition evaluates to true, then the block of code inside the if statements will be executed,
and the block of code inside the else statement will be skipped.

● If the condition evaluates to false, then the block of code inside the if statement is skipped and
the block of code inside the else statement will be executed.
Flowchart of if...else statement

true
condition

false statements
inside if
statements
inside else

statements after
if...else
How if...else statements work?

int num = 0;

cout << "Enter a positive number:"; ● The variable num is retrieved and compared
cin >> num; // -2
against 0.
if (num < 0)
{ ● If the variable num is less than 0, then the
cout << "it is not a positive value\n"; cout statement is executed, skips the cout
} statement inside else, and exits the if
else
statement and starts executing the
{
cout << "it is a positive value\n"; statement(s) after the closed curly brackets.
}

cout << "This statement is always executed\n";


How if...else statements work?

int num = 0;

cout << "Enter a positive number:"; ● The variable num is retrieved and compared
cin >> num; // 6
against 0.
if (num < 0)
{ ● If the variable num is greater than 0, then the
cout << "it is not a positive value\n"; cout statement inside if is skipped, executes
} the cout statement inside else, and exits the
else
if...else statement and starts executing the
{
cout << "it is a positive value\n"; statement(s) after the closed curly brackets.
}

cout << "This statement is always executed\n";


If...else if...else statement

● An if statement can be followed by an optional ● Example:


else if...else statement, which is very
useful when we want to select an outcome
if (age == 16)
based on multiple options or conditions. {
cout << “Sweet sixteen!\n”;
● As soon as one of the conditions controlling the }
else if (age == 18)
if is true, the statement associated with that is {
executed, and the rest of the conditions are cout << “Welcome to adulthood!\n”;
skipped. }
else if (age == 50)
{
● If none of the conditions are true, then the final cout << “The good stuff starts now!\n”;
else statement will be executed. }
else
{
cout << “This is a great age for having fun!\n”;
}
Syntax - if...else if...else statement
● If the condition1 evaluates to true, then
the block of code inside the if statement will if (condition1)
{
be executed, and the block of code inside the
statement1;
else if and else will be skipped. statement2;
}
else if (condition2)
● If the condition2 evaluates to true, then
{
the block of code inside the if statement is statement1;
skipped, the block of code inside the else if will statement2;
}
be executed and the else will be skipped.
.
.
● If both condition1 and condition2 .
else
evaluates to false, the block of code inside if
{
and else if will be skipped and else will be statement1;
executed. }
Flowchart of if...else if...else statement

true statements
Condition 1
inside if

false

Condition 2
true statements
inside else

false

statements statements after


inside else if...else if...else
Example - if...else if...else statement
int num1 = 10; ● In the example, we are finding the greatest of
int num2 = 20; three numbers.
int num3 = 15;

if (num1 > num2 && num1 > num3) ● The first condition checks if num1 is greater
{ than num2 and num3, the second condition
cout << "num1 is greater\n"; checks if num2 is greater than num1 and
} num2, finally the else will be executed if both
else if (num2 > num1 && num2 > num3)
the first and second conditions are false.
{
cout << "num2 is greater\n";
} ● We can use more than one condition by using
else logical AND (&&) and OR(||).
{
cout << "num3 is greater\n";
}

cout << "This statement is always executed.\n";


Activity - Predict the output
int a = 5;
int b = 20;

if (a > b && b == a)
{
cout << "(a > b) && (b == a) - condition is true" << endl;
}
else if (b > a)
{
cout << "(b > a) - condition is true" << endl;
}

if (a > b || !(b == a))


{
cout << "(a > b) || !(b == a) - condition is true" << endl;
}
else
{
cout << "(a > b) || !(b == a) - condition is false" << endl;
}
Activity - Predict the output
int a = 5;
int b = 20;

if (a > b && b == a) FALSE && FALSE


{
cout << "(a > b) && (b == a) - condition is true" << endl;
}
else if (b > a) TRUE
{
cout << "(b > a) - condition is true" << endl;
}

if (a > b || !(b == a)) FALSE || !(FALSE) => FALSE || TRUE


{
cout << "(a > b) || !(b == a) - condition is true" << endl;
}
else
{
cout << "(a > b) || !(b == a) - condition is false" << endl;
}
Switch statement
Switch case statement

● Switch case statement is used when we have multiple conditions that lead to different outcomes.

● We can use lengthy if...else if...else, but it gets messy with more than a few possible outcomes.

● The switch case is a clean and efficient method of handling multiple conditions.
switch (age)
● Example: {
case 16:
cout << “Sweet sixteen!\n”;
break;
case 18:
cout << “Welcome to adulthood!\n”;
break;
case 50:
cout << “The good stuff starts now!\n”;
break;
default:
cout << “This is a great age for having fun!\n”;
break;
}
Syntax - Switch case statement

● The value of a character or an integer switch (variable or an integer expression)


expression given in the switch is compared to {
the value following each of the cases, when case valueOne:
one of the value of the case matches the value // statements
break;
of the variable, the computer executes the
case valueTwo:
block of code from that case. // statements
break;
● The default statement is optional but default:
recommended. It is like the final ‘else’ // statements
break;
statement in an if...else if...else.
}
Syntax - Switch case statement

● The break statement is used inside the switch switch (variable or an integer expression)
to terminate from a case. {
case valueOne:
● When a break statement is reached, switch // statements
break;
terminates and the program starts executing
case valueTwo:
the next line following the switch statement. // statements
break;
● The break statement is optional. If ignored, default:
execution will continue through to subsequent // statements
break;
cases until a break is reached.
}
Example - Switch case statement
● The condition of a switch statement is an
int x = 0;
cin >> x; // 2
integral value (character or integer).

switch (x) ● The block of statements under a case gets


{
case 1:
executed when the condition value matches
cout << "Choice 1 is selected\n"; with the value of a case.
break;
case 2:
cout << "Choice 2 is selected\n";
● In this example, we are using switch case to
break; select between three different options.
case 3:
cout << "Choice 3 is selected\n";
break;
● If the value of x matches with any of the case,
default: it executes the block of statements under the
cout << "did not pick options from 1 to 3.\n"; case until it hits the break statement.
break;
} // choice 2 is selected.
● If user did not select a option between 1, 2 or
3, then the default case is executed.
switch vs if...else if...else
int x = 0;
int x = 0;
cin >> x;
cin >> x;

if (x == 1)
switch (x)
{
{
cout << "Choice 1 is selected\n";
case 1:
}
cout << "Choice 1 is selected\n";
else if (x == 2)
break;
{
case 2:
cout << "Choice 2 is selected\n";
cout << "Choice 2 is selected\n";
}
break;
else if (x == 3)
case 3:
{
cout << "Choice 3 is selected\n";
cout << "Choice 3 is selected\n";
break;
}
default:
else
cout << "did not pick options from 1 to 3.\n";
{
break;
cout << "did not pick options from 1 to 3.\n";
}
}
Nested conditions
Nested Conditions

● We can have conditional statement inside another conditional statement.

● C++ allows nested if and switch statements. i.e., we can place an if statement inside another if
statement.

int num = 0;
cin >> num; if (num >= 0 && num < 50)
{
if (num >= 0) Applies && between cout << "Below 50\n";
{ outer and inner }
if (num < 50) else if (num >= 0 && num >= 50)
condition
{ {
cout << "Below 50\n"; cout << "At least 50\n";
} }
else
{
cout << "At least 50\n";
}
}
Ternary operator
The Ternary operator (?:)

● The ternary operator is shorthand for an if...else statement

int a = 10;
int a = 10;
int b = 20;
int b = 20;
int result = 0;
int result = 0;

result = (a > b) ? a : b;
if (a > b)
{
cout << result << endl;
result = a;
}
else
{
result = b;
}
cout << result << endl;
The Ternary operator (?:)

● Otherwise known as conditional operator, it takes three operands. The conditional operator works as
follows:
○ The first operand is converted to bool.
○ If the first operand evaluates to true (1), the second operand is evaluated.
○ If the first operand evaluates to false (0), the third operand is evaluated.

int a = 10;
int b = 20;
int result = 0; result if result if
condition true false
result = (a > b) ? a : b;
result = (a > b) ? a : b;

● The conditional operator returns the evaluated operand (the second or the third). Only one of the last
two operands is evaluated in a conditional operator.

● The second and the third operands should be of the same type.
Activity - Student Grading

● Open Visual Studio and create new C++ project with the name GradingSystem.

● Creating the following variables: Mark Grade


○ mark (to store student’s marks from 0 to 100).
○ grade (to grade the student’s based on the mark). 0 - 49.99 F
● Get input from the user for the mark to calculate the grade. 50.00 - 64.99 P

● Use the information from the table to calculate the grade. 65.00 - 74.99 C

● Print the grade on to the screen. 75.00 - 84.99 D

85.00 - 100.00 H
● Build and Run the program.
------- Expected Output --------
Enter your mark: 57.45
Your grade is P
Summary

● Conditional statements are used to make decision based on the given condition.

● The if statement selects and executes statement(s) based on the given condition.

● The if...else statement selects and executes one of the two possible statement(s).

● The if...else if...else statement selects and executes one of multiple statement(s).

● The switch statement tests the value of an expression in a sequence and compares it with the list of
integers or character constants. When a match is found, all the statements associated with that value
are executed.

● Nested conditions are condition statements that make decision inside another decision.

● The conditional operators (?:) is a short version of if...else statement that can be written in one
line.
References

Mikeblome. 2019. Microsoftcom. [Online]. [9 July 2019]. Available from:


https://docs.microsoft.com/en-us/cpp/cpp/conditional-operator-q

Geeksforgeeksorg. 2017. GeeksforGeeks. [Online]. [9 July 2019]. Available from:


https://www.geeksforgeeks.org/switch-statement-cc/

Dinesh thakur. 2019. Ecomputernotescom. [Online]. [9 July 2019]. Available from:


http://ecomputernotes.com/cpp/control-structures/conditional-statements

Wikiversityorg. 2019. Wikiversityorg. [Online]. [9 July 2019]. Available from:


https://en.wikiversity.org/wiki/C++/Conditional_Statements

You might also like