Review the following: if-else One branch if Conditional operators Logical operators Switch statement Conditional expression operator Nested ifs if –else if Program using conditional statements
if ( condition ) { //code for true branch } else { //code for false branch } condition True branch False branch TF
if ( x >= y ) { cout << “x is greater than or equal to y”; } else { cout << “x is less than y”; }
> greater than <less than >=greater than or equal <=less than or equal ==equal !=not equal
if (condition) { //true branch } condition True branch TF
if ( x > 7 ) { x = x +3; cout << x; }
&& logical and || logical or ! logical not
if ( a > b && c < d ) { cout << “both conditions true”; } if (x 18 ) {cout << “either condition is true”; if (! Prime) { cout << “ number is not prime”; } (1) (2) (3)
switch (variable) { case a: statements case b: statements default: statements }
switch (x ) { case 6 : cout << “x is 6”; break; case 3 : cout << “x is 3”; break; default: cout << “x is not 6 or 3 “; } x==6 x is 6 x==3 x is 3 x is not 6 or 3 t t f f
(condition) ? true branch : false branch;
Big = (a>b) ? a : b ; a > b Big = aBig = b TF
c > d X=2X=3 t t a>b X=1 f f if (a > b) { if ( c > d) { X = 3; } else { X = 2; } else { X = 1; }
if ( g > 89) cout << “Grade = A”; else if (g > 79 ) cout << “Grade = B”; else if (g > 69) cout << “Grade = C;” else cout << “Grade = “Bad”; g> 89 g > 79 g> 69 Grade = Bad Grade = A Grade = B Grade = C
Find the roots of the quadratic equation ax² + bx + c = 0 The 2 roots are found using the formula: _______ -b ± √ (b²-4ac) a
Start End Prompt for & read in a,b,c D =disciminant D>0 && a != 0 Calculate 2 roots r1,r2 r1,r2 Roots imaginary or a == 0 T F
#include #include using std::cin; using std::cout; using std::endl; int main() { double a, b, c; cout > a >> b >> c; double d = b * b * a * c; if ((d >= 0.0) && (a != 0.0)) { double x1 = (-b + sqrt(d)) / (2.0 * a); double x2 = (-b - sqrt(d)) / (2.0 * a); cout << "x1 = " << x1 << " x2 = " << x2 << endl; } else cout << "the roots are imaginary or a equals 0" << endl; return 0; }
double a, b, c; cout > a >> b >> c;
double d = b * b * a * c;
if ( (d >= 0.0) && (a != 0.0) )
{ double x1 = (-b + sqrt(d)) / (2.0 * a); double x2 = (-b - sqrt(d)) / (2.0 * a); cout << "x1 = " << x1 << " x2 = " << x2 << endl; }
else cout << "the roots are imaginary or a equals 0" << endl;
Review the following: if-else One branch if Conditional operators Logical operators Switch statement Conditional expression operator Nested ifs if –else if Program using conditional statements