Conditional Execution in C++

Conditional Execution

All the programs in the preceding chapters execute exactly the same statements regardless of the input, if any, provided to them. They follow a linear sequence: Statement 1, Statement 2, etc. until the last statement is executed and the program terminates. Linear programs like these are very limited in the problems they can solve.

Type bool

Arithmetic expressions evaluate to numeric values; a Boolean expression, evaluates to true or false. While Boolean expressions may appear very limited on the surface, they are essential for building more interesting and useful programs.

#include <iostream>
int main() {

// Declare some Boolean variables
bool a = true, b = false;
std::cout << "a = " << a << ", b = " << b << '\n';
// Reassign a
a = false;
std::cout << "a = " << a << ", b = " << b << '\n';
// Mix integers and Booleans
a = 1;
b = 1;
std::cout << "a = " << a << ", b = " << b << '\n';
// Assign Boolean value to an integer
int x = a, y = true;
std::cout << "a = " << a << ", b = " << b
<< ", x = " << x << ", y = " << y << '\n';
// More mixing
a = 1725; // Warning issued
b = -19; // Warning issued
std::cout << "a = " << a << ", b = " << b << '\n';

}

Boolean Expressions

The simplest Boolean expressions are false and true, the Boolean literals. A Boolean variable is also a Boolean expression. An expression comparing numeric expressions for equality or inequality is also a Boolean expression.

Relational operator examples

  • 10 < 20 always true
  • 10 >= 20 always false
  • x == 10 true only if x has the value
  • 10 X != y true unless x and y have the same values

Algorithms

An algorithm is a finite sequence of steps, each step taking a finite length of time, that solves a problem or computes a result. A computer program is one example of an algorithm, as is a recipe to make lasagna.

The bitwise assignment operators

x = x & y; x & = y; x = x | y; 
x |= y; x = x ^ y;
 x ^= y; x = x << y;
 x <<= y; x = x >> y; x >>= y; 
#include <iostream>
    int main() {
    double degreesF = 0, degreesC = 0;
    // Define the relationship between F and C
    degreesC = 5.0/9*(degreesF - 32);
    // Prompt user for degrees F
    std::cout << "Enter the temperature in degrees F: ";
    // Read in the user's input
    std::cin >> degreesF;
    // Report the result
    std::cout << degreesC << '\n';
}