The if-else statement in C++ helps the program make decisions by checking conditions. It allows the program to choose what action to take based on whether something is true or false.
How it works:
- if: If a condition is true, the code inside the
ifblock will run. - else: If the condition is false, the code inside the
elseblock will run.
Syntax: - if (condition) {
- // Code to run if condition is true
- } else {
- // Code to run if condition is false
- }
Example: - #include <iostream>
- using namespace std;
- int main() {
- int number;
- cout << "Enter a number: ";
- cin >> number;
- if (number > 0) {
- cout << "The number is positive." << endl;
- } else {
- cout << "The number is not positive." << endl;
- }
- return 0;
- }
Explanation:
- The program asks the user to input a number.
- If the number is greater than 0, it prints "The number is positive."
- If the number is 0 or less, it prints "The number is not positive."
In short:
- if checks a condition.
- else provides an alternative if the condition is false.


Perfect
ReplyDeleteKeep going 💫
ReplyDeleteWow 😮
ReplyDeleteWonderful
ReplyDeletePerfect
ReplyDeleteIt really saved my life 😍😍😍😍
ReplyDeleteGreat work
ReplyDeleteKeep up the good work nicely done
ReplyDeleteSlightly good 👍
ReplyDeleteThanks, Iam gonna try it.
ReplyDelete