C++ if statement
Created By: chatGPT
If statements in C++ are used to execute a block of code based on a condition. If the condition evaluates to true, the code within the block will run. Otherwise, it will be skipped. Here’s the syntax and an example.
if (condition) {
// code to execute if condition is true
}
Let's see a practical example. In the following code, we check if a number is positive or negative.
In this example, the program asks the user to input a number. It then uses an if statement to determine whether the number is positive, negative, or zero, and outputs the appropriate message.#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number > 0) {
std::cout << "The number is positive.";
} else if (number < 0) {
std::cout << "The number is negative.";
} else {
std::cout << "The number is zero.";
}
return 0;
}