English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ if, if...else y if...else anidados

En este artículo, aprenderás a usar diferentes formas de sentencias if..else en C ++Se crean sentencias de decisión en el programa.

Sentencia
Sentencia if
Sentencia if...else
Sentencias if...else anidadas
Operador ternario

C ++ Sentencia if

if (testExpression) 
{
   // Sentencias que se ejecutarán si testExpression es verdadero
}

La sentencia if evalúa testExpression dentro de los paréntesis.

Si el resultado de la cálculo de testExpression es verdadero, se ejecutan las sentencias dentro del cuerpo del if.

Si el resultado de la cálculo de testExpression es falso, se salta las sentencias dentro del cuerpo del if.

¿Cómo funciona la sentencia if?

Diagrama de flujo de la sentencia if

La imagen superior describe el funcionamiento de la sentencia if.

Example1: C ++ Sentencia if

// El programa imprime el número entero positivo ingresado por el usuario
// Si el usuario ingresa un número negativo, se salta
 
#include <iostream>
using namespace std;
int main() 
{
    int number;
    cout << "Enter an integer: ";
    cin >> number;
    // Verificar si el número es positivo
    if (number > 0) 
    {
        cout << "Ingresaste un número entero positivo: " << number << endl;
    }
    cout << "Esta sentencia siempre se ejecuta.";
    return 0;
}

Salida1

Enter an integer: 5
Ingresaste un número entero positivo: 5
Esta sentencia siempre se ejecuta.

Salida2

Enter an integer: -5
Esta sentencia siempre se ejecuta.

C ++ Sentencia if...else

Si la expresión de prueba (test Expression) es verdadera, se ejecuta el código dentro del cuerpo del if...else y se salta el código dentro del cuerpo else.

If the test expression (test Expression) is false, the code in the else statement body is executed, and the code in the if body is skipped.

How does the if...else statement work?

Flowchart of if...else

Example2: C ++ if...else statement

//The program checks if the integer is a positive number or a negative number
//This program considers 0 as a positive number
#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;
    }
    cout << "This line is always printed.";
    return 0;
}

Resultado de salida

Enter an integer: -4
You entered a negative integer: -4.
This line is always printed.

C ++ Nested if...else statements

The if...else statement executes two different pieces of code depending on whether the test expression (Test expression) is true or false. Sometimes, you must choose from more than two possibilities.

Using nested if...else statements, you can check multiple test expressions (Test expression) and execute different code for more than two conditions.

This means you can use another if or else if statement inside a single if or else if statement.

Syntax of nested if...else

if (testExpression1) 
{
   // If testExpression1The statement to be executed if true
}
else if (testExpression2) 
{
   // If testExpression1The statement to be executed if false, testExpression2The statement to be executed if true
}
else{
    if (testExpression 3) 
    {
       // If testExpression1and testExpression2The statement to be executed if false, testExpression3The statement to be executed if true
    }
    else 
    {
       // The statement to be executed if all test expressions are false
    }
}

Example3: C ++ Nested if...else

// The program checks if an integer is positive, negative, or zero
#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
    {
        if (number < 0)
            {
                cout << "You entered a negative integer: " << number << endl;
            }
             cout << "You entered 0." << endl;
        }
    }
    cout << "This line is always printed.";
    return 0;
}

Resultado de salida

Ingrese un entero: 0
Ingresó 0.
Esta línea se imprime siempre.

Condicional/Operador ternario (?:)

Operando del operador ternario3Un operando se puede usar para operar, lo que puede reemplazar la sentencia if...else.

El siguiente código if:

if (a < b) {
   a = b;
}
else {
   a = -b;
}

Puede usar el operador ternario para reemplazar el siguiente código:

a = (a < b) ? b : -b;

El operador ternario es más corto y legible que la condición if...else.