Conditional Statements 1
Conditional Statements 1
• You can use these conditions to perform different actions for different
decisions.
• int main() {
• if (20 > 18) {
• cout << "20 is greater than 18";
• }
• return 0;
• }
• Output 20 is greater than 18
• #include <iostream>
• using namespace std;
• int main() {
• int x = 20;
• int y = 18;
• if (x > y) {
• cout << "x is greater than y";
• }
• return 0;
• }
• x is greater than y
• / Program to print positive number entered by the user
• // If the user enters a negative number, it is skipped
• #include <iostream>
• using namespace std;
• int main() {
• int number;
• cout << "Enter an integer: ";
• cin >> number;
• // checks if the number is positive
• if (number > 0) {
• cout << "You entered a positive integer: " << number << endl;
• }
• cout << "This statement is always executed.";
• return 0;}
• output
• Enter an integer: 5
• You entered a positive number: 5
• This statement is always executed.
The else Statement
• 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
• #include <iostream>
• using namespace std;
• int main() {
• int time = 20;
• if (time < 18) {
• cout << "Good day.";
• } else {
• cout << "Good evening.";
• }
• return 0;
• }
• output:
• Good evening.
• If the condition evaluates true,
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
cout << "You entered a negative integer: " << number << endl;
}
• Here, we enter 4. So, the condition is true. Hence, the statement inside
the body of if is executed.
• Output 2
• Enter an integer: -4
• You entered a negative integer: -4.
• This line is always printed.
• #include <iostream>
• using namespace std;
• int main() {
• int a=10;
• int b= 20;
• int sum=a+b;
• cout<<sum<<endl;
• if (sum < 18) {
• cout << "sum is smaller.";
• } else {
• cout << "sum is greater.";
• }
• return 0;
• }
output
• 30
• sum is greater.