Lesson-4-Conditional-Statements
Lesson-4-Conditional-Statements
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
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:
Output 7
Case 2: Case 3: Case 4: Case 5: Default:
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