Skip to content

Conditional

Conditional control flow

Conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false

1
2
3
if (first_number % 2 == 0) {
    ++n_even_numbers;
}

1
2
// same as: n_even_numbers += second_number % 2 == 0;
n_even_numbers += (first_number % 2 == 0) ? 1 : 0;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
if (n_even_numbers == 0) {
    cout << "You typed 0 even numbers and 2 odd numbers\n";
} else if (n_even_numbers == 1) {
    cout << "You typed 1 even number e 1 odd number\n";
} else if (n_even_numbers == 2) {
    cout << "You typed 2 even numbers e 0 odd numbers\n";
} else {
    cout << "There's a serious problem here\n";
    return 1;
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
switch (n_even_numbers) {
case 0:
    cout << "Zero even numbers. Two odd numbers.\n";
    break;
case 1:
    cout << "One even number and one odd number.\n";
    break;
case 2:
    cout << "Two even numbers. No odd numbers.\n";
    break;
default:
    cout << "We found a serious error with your program\n";
    return 1;
}

1
2
3
4
5
6
7
if (first_number % 2 != 0 && second_number % 2 != 0) {
    cout << "You typed 0 even numbers e 2 odd numbers\n";
} else if (first_number % 2 == 0 && second_number % 2 == 0) {
    cout << "You typed 2 even numbers e 0 odd numbers\n";
} else {
    cout << "You typed 1 even number e 1 odd number\n";
}

1
2
cout << "You typed " << n_even_numbers << " even numbers and "
     << number_of_numbers - n_even_numbers << " odd numbers\n";

1
2
3
4
cout << "You typed " << n_even_numbers << " even number";
cout << (n_even_numbers == 1 ? "" : "s");
cout << " and " << number_of_numbers - n_even_numbers << " odd number";
cout << (number_of_numbers - n_even_numbers == 1 ? "" : "s");

1
2
3
4
5
if (n_even_numbers > number_of_numbers - n_even_numbers) {
    cout << "You have more even numbers\n";
} else {
    cout << "You don't have more even numbers\n";
}

1
2
3
4
cout << "You "
     << ((n_even_numbers > number_of_numbers - n_even_numbers) ? ("")
                                                               : ("don't"));
cout << " have more even numbers than odd numbers\n";

1
2
3
4
5
if constexpr (number_of_numbers > 2) {
    cout << "You're program is not adapted to that yet\n";
} else {
    cout << "Program for testing up to two numbers\n";
}

Share Snippets