KEMBAR78
Unit 3 Conditional Statements in C++ | PDF | Computer Science | Software Development
100% found this document useful (1 vote)
32 views13 pages

Unit 3 Conditional Statements in C++

This document covers conditional statements in C++ including relational, logical, and selection structures such as if, if...else, else...if, and switch statements. It explains the use of relational operators for comparisons, logical operators for combining conditions, and provides examples of each statement type. Additionally, it discusses the order of precedence for operators in C++.

Uploaded by

Roman Saadat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
32 views13 pages

Unit 3 Conditional Statements in C++

This document covers conditional statements in C++ including relational, logical, and selection structures such as if, if...else, else...if, and switch statements. It explains the use of relational operators for comparisons, logical operators for combining conditions, and provides examples of each statement type. Additionally, it discusses the order of precedence for operators in C++.

Uploaded by

Roman Saadat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT 3 Conditional Statements (Selection Structures) in C++

Course Learning Outcomes


*CLO1→C2+: Relational operators used in C++ programs
*CLO2→C2, C3+: Using if, if…else, else…if and switch statements in C++ programs
*CLO3→C2, C3]: Logical operators, compound statements and ternary operator

Introduction

Control statements having a decision are very commonly used in computer programs. These
are also known as selection structures. A selection structure is a programming feature that
performs different tasks based on whether a condition is true or false. The operation of
decisions involves relational expressions that use relational operators. Therefore, we will
examine them first.

Relational Operators

Relational operators are used to compare two values of same data type in a relational
expression. The data can be of type char, int or float. When a relational expression is
evaluated the result produced is true or false. The C++ compiler considers that a true
expression has the value 1, while a false expression has the value 0. Although C++ generates
a 1 to indicate true, it assumes that any value other than 0 (such as -7 or 23) is true.

There are six types of relational operators available in C++ that are used in relational
expressions in decisions. These are given in the following table.

Operator Meaning Example


== Equal to x == y
!= Not equal to a != b
< Less than a < b +5
> Greater than x>y+z
<= Less than or equal to x <= 20
>= Greater than or equal to d >= a + b*3

Evaluation of relational expressions:


jane = 44; // assignment statement
harry = 12; // assignment statement
(jane == harry) // false
(harry <= 12) // true
(jane > harry) // true
(jane >= 44) // true

M. Sajjad Heder Pg. 1


(harry != 12) // false
(0) // false (0 is false)
(44) // true (any number other than 0 is true)

The output statement:


cout << (jane == harry)
will output 0 since it is false.

The output statement:


cout << (jane > harry)
will output 1 as 44 is greater than 12.

The if Statement

The if statement is used to execute a block of statements based on a condition.


The following is the general form of if statement.

if (condition)
{
Block of statements
}

When it is executed, the condition is evaluated. If it is true, the block of statements within
the braces are executed. If the condition is false, the block of statements is skipped and
control is transferred to the next statement after the closing brace. Braces are not required
if there is a single statement to be executed.

#include <iostream>
using namespace std;
int main()
{
int x;
cout << “Enter a number:”;
cin >> x;
if (x > 100)
{
cout << “That number is greater than 100\n”;
}
return 0;
}

In the above program, if the number entered is greater than 100 then the message in the
cout statement will be printed. Braces are used in the if statement but not required as there
is only one statement to be executed if the condition is true.

M. Sajjad Heder Pg. 2


//This program demonstrates the use of 2 statements in an if statement.
#include <iostream>
using namespace std;
int main()
{
int marks;
cout << “Enter marks:”;
cin >> marks;
if (marks >= 60) // passing marks 60
{
cout << “Congratulations!” << endl;
cout << “You passed” << endl;
}
return 0;
}

In this program, two output statements will be executed if marks are greater than or equal
to 60 and the output will be:

Congratulations!
You passed

The if ... else Statement

This statement allows you to do something if a condition is true and do something else if it is
false.

The following is the general form of if … else statement.

if (condition)
{
Block of statements-1
}
else
{
Block of statements-2
}

When if ... else statement is executed, the condition is evaluated. If it’s true the Block of
statements-1 is executed otherwise Block of statements-2 is executed.

#include <iostream>
using namespace std;
int main()
{
int x;

M. Sajjad Heder Pg. 3


cout << “Enter a number:”;
cin >> x;
if (x > 100)
{
cout << “That number is greater than 100”;
}
else
{
cout << “That number is not greater than 100”;
}
return 0;
}

If the condition x > 100 is true, the first message will be printed otherwise the second
message will be printed.

The else . . . if Statement

This statement allows to do something from many alternatives based on various conditions.

The following is the general form of else . . . if statement.

if (condition-1)
{
Block of statements-1
}
else if (condition-2)
{
Block of statements-2
}
.
.
.
else
{
Block of statements-n
}

When else . . . if statement is executed, the condition-1 is evaluated. If it’s true the Block of
statements-1 is executed. If condition-1 is false then condition-2 is evaluated. If it is true
then block of statements-2 is executed. In this way conditions are evaluated one-by-one.
When any condition is true, the block of statements following that condition is executed and
the control is transferred to the next statement. If all the conditions are false then the last
block of statements following the keyword else is executed. The else block is optional.

M. Sajjad Heder Pg. 4


//Program to print letter grade to demonstrate the use of else . . . if statement.
#include <iostream>
using namespace std;
int main()
{
int m;
cout << “Enter the marks:”;
cin >> m;
if (m >= 90 )
{
cout << “Grade A”;
}
else if (m>=80)
{
cout << “Grade B”;
}
else if (m>=70)
{
cout<< ”Grade C”;
}
else if (m>=60)
{
cout<< “Grade D”;
}
else //marks less than 60
{
cout<< “Grade F”;
}
return 0;
}

The switch Statement

The switch statement is similar to else ... if statement. It is used when a block of statements
is to be executed among many options.
The following is the general form of switch statement.

switch (variable/expression)
{
case const-1: Block of statements-1
break;
case const-2: Block of statements-2
break;
case const-3: Block of statements-3
break;
.
.
.

M. Sajjad Heder Pg. 5


default: Block of statements-n;
}
The expression is evaluated. The result of expression or the value of the variable is
compared one by one with the constant values given after the keyword case. If result
matches any constant value then the block of statements following that case is executed. If
none of the constant values matches then the block of statements following the keyword
default is executed. The break statement causes the control to transfer to the next
statement after the case statement. Use of default is optional.

The break Statement

The break statement is used to terminate a switch or a loop and the program execution
continues from the next statement following it. Loops will be discussed in unit 4.

// Program that reads an integer between 1 to 7 that represents a day of


// week starting from Monday and prints the name of the day based on the
// value of day.
#include <iostream>
using namespace std;
int main()
{ int a;
cout << “Enter an integer (1 to 7):”;
cin >> a;

switch(a)
{
case 1: cout<<”\nMonday”<<endl; break;
case 2: cout<<”\nTuesday”<<endl; break;
case 3: cout<<”\nWednesday”<<endl; break;
case 4: cout<<”\nThursday”<<endl; break;
case 5: cout<<”\nFriday”<<endl; break;
case 6: cout<<”\nSaturday”<<endl; break;
case 7: cout<<”\nSunday”<<endl; break;
}
return 0;
}

// Program that reads a character and verifies it.


#include <iostream>
using namespace std;
int main()
{
char ch;
cout << “Enter a character (a, b, c or d):”;
cin >> ch;

M. Sajjad Heder Pg. 6


switch(ch)
{
case ‘a’:
case ‘b’:
case ‘c’: cout<<”\nYou entered a, b or c”; break;
case ‘d’: cout<<”\nYou entered d”; break;
default: cout<<”\n*** Invalid Data ***”;
}
return 0;
}

The above program reads a character and if it is a, b or c then it prints the same message

You entered a, b or c

If it is d it prints the message

You entered d

It prints the following message if the entered character is not a, b, c or d.

*** Invalid Data ***

//Program to perform basic arithmetic using switch statement.


#include <iostream>
using namespace std;
int main()
{ int x, y;
char oper;
cout << “Enter 2 numbers, x and y:”;
cin >> x>>y;
cout << “Enter the operator (+, -, *, /,%)”;
cin >> oper;

switch(oper)
{
case ‘+’: cout<<”\nx+y=” <<x+y; break;
case ‘-‘: cout<<”\nx-y=” <<x-y; break;
case ‘*’: cout<<”\nx*y=” <<x*y; break;
case ‘/’: cout<<”\nx/y=” <<x/y; break;
case ‘%’: cout<< “\nx%y=” <<x%y; break;
default: cout<<”\n****** Invalid Data ******”;
}

return 0;
}

M. Sajjad Heder Pg. 7


The Logical Operators

The logical operators are used when some action is to be taken based on more than one
condition.

There are three types of logical operators.

Logical Operator Definition


&& AND
|| OR
! NOT

Logical AND (&&) Operator

The logical AND operator is used with two relational expressions, one on the left and the
other on the right of the operator. If both of the relational expressions are true then the
compound condition is true otherwise it is false.

Example: (a>b)&&(c==5)

When this compound condition is evaluated, it will produce true if a is greater than b and c
is equal to 5 otherwise the result will be false.

The following compound condition will check whether the character stored in variable ch is
a lowercase letter or not.

(ch>=’a’)&&(ch<=’z’)

The following is the truth table of AND operator.

Expression-1 Expression-2 Expression1 && Expression-2


False False False
False True False
True False False
True True True

//Program to read a character and print whether it is a lower-case or


//an upper-case letter.
#include <iostream>
using namespace std;
int main()
{

M. Sajjad Heder Pg. 8


char ch;
cout << “Enter a character:”;
cin >> ch;
if (ch >= ‘a’ && ch <= ‘z’ )
{
cout << “\nYou entered a lower-case letter.” <<endl;
}
else if (ch >= ‘A’ && ch <= ‘Z’)
{
cout << “\nYou entered an upper-case letter.” <<endl;
}
else
{
cout<< “\nYou did not enter lower-case or upper-case letter.”<<endl;
}
return 0;
}

Logical OR (||) Operator

The OR operator is used with two relational expressions, one on the left and the other on
the right of the operator like the AND operator. The compound condition is true if either of
the conditions is true or both are true. It is false only if both of the conditions are false.

Example: (a>b)||(c==d)

The compound condition will be true if either a is greater than b or c is equal to d or both
are true. It will only be false when a is not greater than b and c is not equal to d. The
following is the truth table of OR operator.

Expression-1 Expression-2 Expression1 || Expression-2

False False False

False True True

True False True


True True True

//This program reads 4 integers to demonstrate the use of OR operator.


#include <iostream>
using namespace std;
int main()
{
int a, b, c, d;
cout << ”\nEnter 4 integers:”;

M. Sajjad Heder Pg. 9


cin>>a>>b>>c>>d;
if( a>b || c==d)
{
cout << ”\nEither a is greater than b or c is equal to d”
<< “\nor both conditions are true, that is,”
<< “\na is greater than b and c is equal to d.”<<endl;
}
else
{
cout << “\na is not greater than b and c is not equal to d.”<<endl;
}
return 0;
}

Logical NOT (!) Operator

The NOT operator is used with a single condition. It produces true if the condition is false
and false if the condition is true. It reverses the result of a single relational expression.

Example: !(a>b) It is equivalent to (a<=b)

It will produce true if a is not greater than b. In other words, it will be true if a is less than or
equal to b. The following is the truth table of AND operator.

Expression !Expression

False True

True False
//Program to demonstrate the use of NOT operator.
#include <iostream>
using namespace std;
int main()
{
int marks;
cout << ”\nEnter marks:”;
cin >> marks;

if( !(marks < 50)) //If marks not less than 50


{
cout << ”\nCongratulations!”;
cout << “\nYou have passed.” << endl;
}
else
{
cout << “\nYou have failed.”<<endl;

M. Sajjad Heder Pg. 10


}
return 0;
}

Order of Precedence of Operators

The order of precedence of operators is shown in the following table. The operator that has
the highest precedence is written at the top and the one with the lowest precedence is
written at the bottom.

Precedence Operator Description


1. ++, -- Increment and Decrement (Prefix or Postfix)
2. *, /, % Multiplication, Division, Remainder
3. +, - Addition, Subtraction
4. <, <=, >, >= Relational Operators
5. ==, != Equal to and Not Equal to
6. ! Logical NOT
7. && Logical AND
8. || Logical OR
9. =, *=, /=, %=, +=, -= Assignment Operators

If an expression contains two or more operators of the same precedence then the
operations are performed from left to right in the order in which they appear.

For example,
7 * 10 – 5 % 3 * 4 + 9 / 3
The leftmost multiplication is performed first, giving
70 – 5 % 3 * 4 + 9 / 3
The next high-priority operation from left to right is % which gives
70 – 2 * 4 + 9 / 3
Multiplication will be performed next
70 – 8 + 9 / 3
The next high-priority operations is division, it gives
70 – 8 + 3
Subtraction will be performed next, giving
62 + 3
Now addition will be carried on giving the result 65

The standard order of evaluation can be modified by using brackets to enclose part of an
expression. The part of the expression within the brackets is first evaluated and then result
is combined to evaluate the complete expression.

M. Sajjad Heder Pg. 11


For example, in the expression
a / (b + c)
b + c will be performed first and then a will be divided by the sum of b and c.

If the brackets are nested, that is, if one set of brackets is contained within another, then
the computations in the innermost brackets are performed first.

Nested Selection Structure

The selection structure that is within another selection structure is known as nested
selection structure. Sometimes in programming, it is required to use a selection structure
within another selection structure. C++ allows programmers to have selection structure (if,
if…else, else…if or switch statement) within another selection structure.

//This program demonstrate the use of nested if…else structure.


//It checks whether the entered number is an odd or even number.
#include <iostream>
using namespace std;

int main()
{
int n;
cout << “\nEnter an integer:”;
cin >> n;
if (n > 0 )
{
cout << “\nYou entered a positive number.”<<endl;
if (n %2 == 0)
{
cout << “\nIt is an even number.”<<endl;
{
else
{
cout << “\nIt is an odd number.”<<endl;
}
}
else
cout<< “\nYou entered a negative number or zero.”<<endl;
return 0;
}

M. Sajjad Heder Pg. 12


The Conditional (Ternary) Operator

A conditional operator is a decision-making operator. It is similar to if…else statement but


takes less space and helps to write the if…else in the shortest way. It is also known as
ternary operator.

It has the general form:

variable = condition? expression1:expression2;

When it is executed, the condition is evaluated. If it is true, then expression1 is evaluated


and the result is assigned to the variable. If the condition is false, then expression2 is
evaluated and the result is assigned to the variable.

It is same as:

if (condition)
{
variable=expression1;
}
else
{
variable=expression2;

Example:

x = (n==10)? a*b : a+b;

If n is equal to 10 then x will be assigned the product of a and b otherwise it will be assigned
the sum of a and b.

It is same as:

if(n==10)
{
x=a*b;
}
else
{
x=a+b;
}

Prepared by: M. Sajjad Heder

M. Sajjad Heder Pg. 13

You might also like