C++ Lec9-If, Else Conditions
C++ Lec9-If, Else Conditions
You can use these conditions to perform different actions for different decisions.
The if Statement
Use the if statement to specify a block of C++ code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the
condition is true, print some text:
Example
#include <iostream>
int main() {
return 0;
Example
#include <iostream>
int main() {
int x = 20;
int y = 18;
if (x > y) {
return 0;
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using the
> operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen
that "x is greater than y".
C++ Else
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
return 0; }
Programming C++ Samir Bilal Practical & Theoretical
5
C++ Else If
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
#include <iostream>
using namespace std;
int main() {
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening."; // Outputs "Good evening."
}
return 0;
}
Programming C++ Samir Bilal Practical & Theoretical
6
Q1) C++ supports the usual logical conditions from mathematics what are them?
Some Exercises:
1) Write a C++ program to read two numbers then print the minimum number between
both (if both numbers are equal print they are equals).
2) Write a C++ program to read a student subject mark, if the mark is greater or equals
to 50 print (Pass) else if it is smaller than 50 print (Fail).
3) Write a C++ program to read the number of work hours if it is less than or equals to 50
, the employee will not get to part time salary, if it is greater than 50 the employee will
get to 20$ as apart time work, the salary of an hour = 5$.
4) Write a C++ program to enter two numbers then test them if they are equals or not.
5) Write a C++ program to enter a number and test it then print (positive) if it is positive
else print (negative).
6) Write a C++ program to read a number then test it, if the number is even print (Even),
else if it is odd print (Odd).