Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Lesson-4-Conditional-Statements

Uploaded by

TwøZerø
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lesson-4-Conditional-Statements

Uploaded by

TwøZerø
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

IT102 – Fundamentals of Programming

Lesson 4 – Conditional Statements

LEARNING CONDITIONAL STATEMENT


OBJECTIVES Conditional Statements in C programming
are used to make decisions based on the
At the end of the module, the I.T. students will be conditions. Conditional statements execute
able to: sequentially where there is no condition around the
statements. If you put some condition for a block of
a. Understand the functions of each statements, the execution flow may change based on
statements the result evaluated by the condition. This process is
b. Evaluate the sequence of the program called decision making in C1.
c. Analyse the output of each statements
d. Create and apply conditional statements
Conditional statement generally involve 1 or more
variables whose values determine the truth and falsity
TOPIC of the statement.
OUTLINE Three Ways of Writing Conditional Statements
Conditional Statements 1. Conditional Variable – take the value of 0
a. if statement (false) or 1 (true) and interpreted as a false or
true.
b. if-else statement
2. Relational Conditional Expression – states a
c. else-if statement relationship.
d. switch statement Example:
Grade >=75
OVERVIEW 3. Complex Conditional Expression – formed by
combining conditional expressions using the
This lesson discuss the conditional logical operators && (and), || (or) and !(not).
statement in programming C used to make decisions Example:
based on the conditions. You will be able to ((grade>=95) && (grade<=99))
understand and appreciate the execution flow based
on the result evaluated by the condition. Where you C++ supports the usual logical conditional from
mathematics:
will define the conditional statements such as if
 Less than: a < b
statement, if else statement, nested if-else statement
 Less than or equal to: a <= b
and switch statement. You will also analyse the flow  Greater than: a > b
of execution, and create programs using conditional  Greater than or equal to: a >= b
statements.  Equal to: a == b
 Not Equal to: a != b
This lesson will serve as a guide as we progress
through the looping statement. Before you continue You can use these conditions to perform different
reading this module, let us first see what you know on actions for different decisions.
this topic.
C++ has the following conditional statements:
 Use if to specify a block of code to be
ACTIVATING executed, if a specified condition is true.
PRIOR KNOWLEDGE  Use else to specify a block of code to be
executed, if the same condition is false.
In 3 to 5 sentences write what you know about  Use else if to specify new condition to test, if
conditional or decision statement? the first conditional is false
 Use switch to specify many alternative
blocks of code to be executed.

Lesson 4 – Conditional Statements | Page 1 of 10


Difference between Simple Statement and Example 1: if statement
Compound Statement #include<iostream>
1. Simple Statement – statement with a single using namespace std;
action. int main()
Example: {
int x = 20;
if (condition) int y = 10;
<statement>; if (x > y) {
cout << x << “ is greater than “ << y;
2. Compound Statement – sequence of two return 0;
or more statements which are grouped }
together. It is introduced by open { and close
} curly braces. Output 1:
Example:
20 is greater than 10
if (condition) {
<statement>; The above program illustrates the use of if construct
<statement>; to check equality of two numbers.
<statement>;
} #include<iostream>
using namespace std;
IF STATEMENT int main()
{
It is one of the powerful conditional 1
int x = 20;
statement. If statement is responsible for int y = 10;
modifying the flow of execution of a program. If if (x > y) {
statement is always used with a condition. The
2
3 cout << x << “ is greater than “ << y;
condition is evaluated first before executing any return 0;
statement inside the body of If. }

The statements inside the body of “if” only execute if 1. In the above program, we have initialized two
the given condition returns true. If the condition variables with x, y with value as 20, 10
returns false then the statement inside “if” are respectively;
skipped. 2. The, we have used if with a test-expression
to check which number is the smallest and
Syntax which is the largest. We have used a
relational expression in if construct. Since the
if (condition) {
// block of code to be executed
value of x is greater than y, the condition will
// if the condition is true. evaluate to true.
} 3. Thus it will print/display the statement inside
the block of if. After that, the control will go
NOTE: outside of the block and program will be
if is in lowercase letters. Uppercase letters (If or IF) terminated with a successful result.
will generate an error.
Example 2: Multiple if statements
Flow Diagram of if statement #include<iostream>
using namespace std;
Before if statement
int main()
{
int x, y;
true
if condition cout << “Enter value of X: “;
cin >> x;
cout << “Enter value of Y: “;
if code block cin >> y;
false if (x > y) {
cout << “ X is greater than Y “ ;
}

After if statement

Lesson 4 – Conditional Statements | Page 2 of 10


Flow Diagram of if else statement
if (x == y) {
cout << “ X is equal to Y “ ;
} Before if else statement
.
cout << “End of Program”;
return 0;
} true
if condition

Output 2-1:
false code inside if body
Enter value of X: 50
Enter value of Y: 30
code inside else body
X is greater than Y
End of Program

Output 2-2:
After if else statement
Enter value of X: 15
Enter value of Y: 45X
is less than Y Example 3: if else statement
End of Program This program user is asked to enter the age and
based on the input, the if..else statement checks
Output 2-3: whether the entered age is greater than or equal to
18. If this condition meet then display message “You
Enter value of X: 90
are eligible for voting”, however if the condition
Enter value of Y: 90 X
is equal to Y
doesn’t meet then display a different message “You
End of Program are NOT eligible for voting”.
#include<iostream>
using namespace std;
int main()
IF ELSE STATEMENT {
If condition returns true then the statements int age;
inside the body of “if” are executed and the cout << “Enter your age: “;
statements inside body of “else” are skipped. If cin >> age;
condition returns false then the statements inside the if (age >= 18) {
body of “if” are skipped and the statements in “else” // this statement will only execute if the
are executed. // above condition (age>=18) returns true
cout << “You are eligible for voting “;
Syntax: }
else {
if (condition) { // this statement will only execute if the
// statements inside body of if // condition specified in the “if” returns false.
} cout << “You are NOT eligible for voting “;
else { }
// statements inside body of else return 0;
} }

Output 3:

Enter your age: 14


You are NOT eligible for voting

Lesson 4 – Conditional Statements | Page 3 of 10


Example 4: if else statements Flow Diagram of else..if statement

#include<iostream> Before else…if statement


using namespace std;
int main()
{ true
if condition 1
int x, y;
cout << “Enter value of X: “;
cin >> x; false Execute statement
cout << “Enter value of Y: “;
cin >> y;
if condition 2 true
if (x > y) {
cout << x <<” is greater than “ << y ;
}
false Execute statement
else {
cout << x << “ is less than “ << y ;
} if condition 3 true
return 0;
}
false Execute statement
Output 4-1:
code inside else body
Enter value of X: 10
Enter value of Y: 25
10 is less than 25

Output 4-2: After else…if statement

Enter value of X: 40 Example 5: else…if statement


Enter value of Y: 10 #include<iostream>
40 is greater than 10 using namespace std;
int main()
{
ELSE…IF STATEMENT OR int var1, var2;
IF…ELSE LADDER cout << “Input the value of Var1: “;
cin >> var1;
The else…if statement is useful when you
cout << “Input the value of Var2: “;
need to check multiple conditions within the cin >> var2;
program. The statement executes two different if (var1 == var2) {
codes depending upon whether the test expression cout << “Var1 is equal to Var2”;
is true or false. Sometimes, a choice has to be made }
from more than 2 possibilities. else if (var1 > var2) {
cout << “Var1 is greater than Var2”;
The if…else ladder allows you to check between }
multiple test expressions and execute different else if (var2 > var1) {
statements. cout << “Var2 is greater than Var1”;
}
Syntax: else {
if (condition 1) { cout <<”Var1 is NOT equal to Var2 “;
// statements would execute if the condition 1 is true }
} return 0;
else if (condition 2) { }
// statements would execute if the condition 2 is true
} Output 5.1
else if (condition 3) {
// statements would execute if the condition 3 is true Input the value of Var1: 20
} Input the value of Var2: 35
else { Var2 is greater than Var1
// statements would execute if ALL the condition are false
}

Lesson 4 – Conditional Statements | Page 4 of 10


Output 5.2 The expression is evaluated once and compared
with the values of each case label.
Input the value of Var1: 90
 If there is a match, the corresponding
Input the value of Var2: 90
statements after the matching label are
Var1 is equal to Var2
executed. For example, if the value of the
Output 5.3 expression is equal to constant2,
Input the value of Var1: 60 statements after case constant2: are
Input the value of Var2: 20 executed until break is encountered.
Var1 is greater than Var2  If there is no match, the default statements
As you can see that only the statements inside the are executed.
body of “if” are executed. This is because in this  If we do not use break, all statements after
statement as soon as condition is satisfied, the the matching label are executed.
statements inside that block are executed and the  The default clause inside the switch
rest of the blocks are ignored. statement is optional.

Example 6: switch statement


SWITCH STATEMENT
#include <iostream>
The switch statement allows the user to using namespace std;
execute one code block among many int main()
alternatives. It also used when we have multiple {
options and we need to perform a different task for int num=5;
each option. switch(num) {
case 1: cout<<"Case1: Value is: "<<num<<endl;
You can do the same thing with the if…else…if case 2: cout<<"Case2: Value is: "<<num<<endl;
ladder. However, the syntax of the switch statement case 3: cout<<"Case3: Value is: "<<num<<endl;
is much easier to read and write. default: cout<<"Default: Value is: "<<num<<endl;
}
Syntax: return 0;
}
switch (expression) {
case constant1: Output 6
// statements
Default Value is 5
break;
case constant2: In example 6, variable num value is 5 and evaluated
// statements in the constant value of cases. Since there is no
break; case defined with value 5 the default case is
. executed.
.
default: Example 7: switch statement
// default statements
#include <iostream>
}
using namespace std;
Flow Diagram of switch statement int main()
{
Int var1=2;
switch(var1) {
case 1: cout<<"Case 1: “;
case 2: cout<<"Case 2: “;
case 3: cout<<"Case 3: ";
case 4: cout<<"Case 4: ";
case 5: cout<<"Case 5: ";
default: cout<<"Default: “;
}
return 0;
}

Output 7
Case 2: Case 3: Case 4: Case 5: Default:

Lesson 4 – Conditional Statements | Page 5 of 10


Example 7, var1 passed a variable to switch, the Example 9: switch statement use character
value of the variable is 2 so the control jumped to the #include <iostream>
case 2. However, there are no such statements in using namespace std;
the above program which could break the flow after int main()
the execution of case 2. That’s the reason after case {
2, all the subsequent cases and default statements char ch='b';
got executed. switch(ch) {
case 'd': cout<”No ";
Break statement in switch case break;
Break statement are useful when you want your case 'b': cout<<"Yes ";
break;
program-flow to come out of the switch body.
case 'x': cout<<"When ";
Whenever a break statement is encountered in the
break;
switch body, the control comes out of the switch
case 'y': cout<<"What ";
case statement. break;
default: cout<<"Why ";
Example 8: switch statement with break }
#include <iostream> return 0;
using namespace std; }
int main()
{
Int var1=2;
switch(var1) { Output 8
case 1: cout<<"Case 1 “; Yes
break;
case 2: cout<<"Case 2 “;
More Examples:
break;
case 3: cout<<"Case 3 ";
break; Example 10: if…else statement
case 3: cout<<"Case 4 "; Write a program to check whether a give number is
break; even or odd.
default: cout<<"Default “; #include <iostream>
} using namespace std;
return 0; int main()
} {
int x;
cout <<”Enter number: “;
cin >> x;
Output 8
if (x % 2 == 0 ) {
Case 2 cout <<”EVEN number “;
Example 8, var1 passed a variable to switch, the }
value of the variable is 2 so the control jumped to the else {
case 2. The program executes the case 2 statement cout <<”ODD number “;
}
and encountered break statement. Therefore, the
return 0;
control comes out of the switch case statement.
}
Note: Output 10
 Case doesn’t always need to have order
Enter number: 7
1,2,3 and so on. They can have any integer ODD number
value after case keyword. Also, case doesn’t
need to be ascending order always, you can
specify them in any order as per the need of
the program.
 You can also use characters in switch.

Lesson 4 – Conditional Statements | Page 6 of 10


Example 11: if statement #include <iostream>
Write a program to check whether a given number is using namespace std;
positive or negative. int main()
#include <iostream> {
using namespace std; int b1, b2;
int main() cout <<”Enter first number: “;
{ cin >> b1;
int x; cout <<”Enter second number: “;
cout <<”Enter whole number: “; cin >> b2;
cin >> x; if (b1 == b2 ) {
if (x >= 0 ) { cout <<”Two integers are EQUAL“;
cout <<”POSITIVE number “; }
} else {
If (x < 0) { cout <<”Two integers are NOT EQUAL “;
cout <<”NEGATIVE number “; }
} return 0;
return 0; }
} Output 13.1
Output 11 Enter first number: 10
Enter first number: 40
Enter whole number: 10
Two integers are NOT EQUAL
POSITIVE number
Output 13.2
Enter first number: 75
Enter first number: 75
Example 12: if statement
Two integers are EQUAL
Write a program to accept two integers and check
whether they are equal or not.
Example 14: if…else…if statement
#include <iostream>
Write a program to enter temperature in centigrade
using namespace std;
and display a suitable message according to
int main()
temperature state below:
{
It’s Very Hot It’s Very Hot
int n1, n2;
cout <<”Enter first number: “; Less than 0 Freezing Weather
cin >> n1; 0 – 10 Very Cold Weather
cout <<”Enter second number: “; 11 – 20 Cold Weather
cin >> n2; 21 – 30 Normal in Temperature
if (n1 == n2 ) { 31 – 40 It’s Hot
cout <<”Two integers are EQUAL“; Above 41 It’s Very Hot
}
#include <iostream>
If (n1 != n2) {
using namespace std;
cout <<”Two integers are NOT EQUAL “;
int main()
}
{
return 0;
int =temp;
}
cout <<”Enter Temperature: “;
Output 12.1 cin >> temp;
Enter first number: 25 if (temp < 0 ) {
Enter first number: 30 cout <<”Freezing Weather“;
Two integers are NOT EQUAL }
else if ((temp >= 0 ) && (temp <=10)) {
Output 12.2 cout <<”Very Cold Weather“;
Enter first number: 99 }
Enter first number: 99 else if ((temp >= 11 ) && (temp <=20)) {
Two integers are EQUAL cout <<”Cold Weather“;
}
Example 13: if . . . else statement else if ((temp >= 21 ) && (temp <=30)) {
Write a program to accept two integers and check cout <<”Normal Temperature“;
whether they are equal or not. }

Lesson 4 – Conditional Statements | Page 7 of 10


else if ((temp >= 31 ) && (temp <=40)) { Example 16: switch statement
cout <<”Its HOT“; Write a program that will accept any day number in
} integer and display day name in word. Otherwise,
else if (temp >= 41 ) { display invalid day.
cout <<”Its Very Hot“; #include <iostream>
} using namespace std;
return 0; int main()
} {
Output 14 int day;
cout <<”Enter DAY: “;
Enter temperature: 14 cin >> day;
Cold Weather switch (day) {
case 1: cout <<” SUNDAY”; break;
Example 15: if statement case 2: cout <<” MONDAY”; break;
Write a program that will accept a grade of the case 3: cout <<” TUESDAY”; break;
student and declare the equivalent description stated case 4: cout <<” WEDNESDAY”; break;
below. case 5: cout <<” THURSDAY”; break;
GRADE DESCRIPTION case 6: cout <<” FRIDAY”; break;
E Excellent case 7: cout <<” SATURDAY”; break;
default: cout <<”INVALID DAY”;
V Very Good
}
G Good return 0;
A Average }
F Failed
Output 16.1
#include <iostream>
using namespace std; Enter DAY: 4
int main() WEDNESDAY
{
Output 16.2
char grade;
cout <<”Enter Grade: “; Enter DAY: 9
cin >> grade; INVALID DAY
if ((grade == ‘E’) ||(grade == ‘e’)) {
cout <<”Excellent“;
} Example 17: if statement
if ((grade == ‘V’) ||(grade == ‘v’)) { Write a program that will accept gender of a person
cout <<”Very Good“; and display the equivalent description as stated
} below: Otherwise, display invalid gender
if ((grade == ‘G’) ||(grade == ‘g’)) { GENDER DESCRIPTION
cout <<”Good“; F Female
} M Male
if ((grade == ‘A’) ||(grade == ‘a’)) {
#include <iostream>
cout <<”Average“;
using namespace std;
}
int main() {
if ((grade == ‘F’) ||(grade == ‘f’)) {
char kasarian;
cout <<”Failed“;
cout <<”Enter Gender: “;
}
cin >> kasarian;
return 0;
if ((kasarian == ‘F’) || (kasarian == ‘f’)) {
}
cout << “FEMALE “;
Output 15.1 }
if ((kasarian == ‘M’) || (kasarian == ‘m’)) {
Enter Grade: G
cout << “MALE “;
Good
}
Output 15.2 if ((kasarian != ‘M’) && (kasarian 1= ‘m’) &&
Enter Grade: e (kasarian != ‘F’) && (kasarian != ‘f’)) {
Excellent cout << “INVALID GENDER “;
Output 15.3 }
return 0;
Enter Grade: S }

Lesson 4 – Conditional Statements | Page 8 of 10


Output 17 Output 19
Enter Gender: F Enter Gender: K
FEMALE Invalid Gender

Example 18: if . . . else statement


Write a program that will accept gender of a person LEARNING ACTIVITY
and display the equivalent description as stated
below: Otherwise, display invalid gender
GENDER DESCRIPTION Instruction: Using your own Laptop /
F Female Desktop / Cellphone create a program using
M Male conditional statements in answering the given
#include <iostream> problems below.
using namespace std;
int main() { 1. Create a program that accept the year of a
char kasarian; student in number and outputs the sentence,
cout <<”Enter Gender: “; “You are a Freshman”, if the input is 1,”You
cin >> kasarian; are a Sophomore”, if the input is 2, “You are a
if ((kasarian == ‘F’) || (kasarian == ‘f’)) { Junior” if the input is 3 and “You are a Senior”
cout << “FEMALE “; if the input is 4. Use IF STATEMENT.
}
else if ((kasarian == ‘M’) || (kasarian == ‘m’)) { 2. Create program that outputs the chemical
cout << “MALE “; element based on the chemical symbol given.
}
else
Use If…else …if STATEMENT:
cout << “INVALID GENDER “; Symbol Element
} C – Carbon,
return 0; H – Hydrogen,
} N – Nitrogen,
O – Oxygen
Output 18
Enter Gender: m 3. Create a case program that outputs the name
MALE of the polygon [plane figure bounded by
straight line] based on the number of sides
Example 19: switch statement given. Use Switch Case Statement
Write a program that will accept gender of a person No. of Sides Name of Polygon
and display the equivalent description as stated 3 Triangle
below: Otherwise, display invalid gender 4 Quadrilateral
GENDER DESCRIPTION
F Female 5 Pentagon
M Male 6 Hexagon
7 Heptagon
#include <iostream>
using namespace std; 8 Octagon
int main() { 9 Nonagon
char sex; 10 Decagon
cout <<”Enter Gender: “;
cin >> sex;
switch (sex) { 4. Create program that corresponds a number
case ‘F’: to a month. Use If…else Statement
case ‘f’: cout <<” FEMALE”; break; Example
case ‘M’: Enter number: 1
case ‘m’: cout <<” MALE”; break;
1 corresponds to January
default: cout << “Invalid Gender”;
}
return 0;
}

Lesson 4 – Conditional Statements | Page 9 of 10


5. Program that will accept your grade in value
and display the equivalent grade in letter. Use 3. ^ Beginners Book; if Statement in C Programming
IF Statement, IF … ELSE… Statement and with example; Date Retrieved: 12/11/2020;
SWITCH CASE Statement. https://beginnersbook.com/2014/01/c-if-statement/
Grade in Value Grade in Letter
75 below Grade [D] 4. ^ Programiz; C if…else Statement; Date retrieved:
75—85 Grade [C] 12/11/2020; https://www.programiz.com/c-
86—95 Grade [B] programming/c-if-else-statement
96—99 Grade [A]
Example
Enter Grade in Value: 87 Prepared by:
GRADE [B]
JULIE ANN L. MALICAY, MIT
Faculty, College of Information and Technology
SUMMARY Education

Let us see if you can remember the main


points raised in this lesson. Below is a summary of
these points:

 Decision making or branching statements


are used to select one path based on the
result of the evaluated expression.
 C++ provides if, if-else constructs for
decision making statements.
 We can also nest if-else within one another
when multiple paths have to be tested.
 The else-if ladder is used when we have to
check various ways based upon the result of
the expression.
 A switch is a decision making construct in C.
 A switch is used in a program where multiple
decisions are involved.
 A switch must contain an executable test-
expression.
 Each case must include a break keyword
 Case label must be constants and unique.
The default is optional
 Multiple switches statements can be nested
within another.

REFERENCES
1. ^ Guru99 2020; C Conditional Statement: IF, IF
Else and Nested IF else with Examples; Date
Retrieved: 12/07/2020; https://cutt.ly/lhAmCjp

2. ^ W3Schools; C++ Conditions and If Statements;


Date Retrieved: 12/11/2020;
https://cutt.ly/VhAmBsZ

Lesson 4 – Conditional Statements | Page 10 of 10

You might also like