CH 6 Part 2
CH 6 Part 2
CH 6 Part 2
• simple if
• if-else
• if-else-if
repeat(100){
cin >> command;
switch(command){
case 'f': forward(100);
break;
case 'r': right(90);
break;
case 'l': left(90);
break;
default: cout << "Not a proper command, " << command
<< endl;
}
}
}
Remarks
• Statement is error-prone, because you
may forget to write break.
• Falls-through in the absence of break.
repeat(100){
cin >> command;
switch(command){
case 'f': forward(100);
case 'r': right(90);
break;
case 'l': left(90);
default: cout << "Not a proper command, " <<
command << endl;
Logical Data
• We have seen that we can “evaluate” conditions,
combine conditions.
• Why not allow storing the results (true or false) of
such computations?
• Indeed, C++ has data type bool into which values
of conditions can be stored.
• bool is named after George Boole, who formalized
the manipulation of conditions/logical data.
• An int variable can have 2^32 values, a bool
variable can have only two values (true/false)
The data type bool
bool highincome, lowincome;
• Defines variables highincome and lowincome
of type bool.
highincome = (income > 800000);
bool fun = true;
• Will set highincome to true if the variable income
contains value larger than 800000.
• true and false : boolean constants.
• boolean variables which have a value can be used
wherever “conditions” are expected, e.g.
if(highincome) tax = …
An Example
main_program {
int x; cin >> x; // read x 4534534536
int i = 2; //first factor to check;
bool factorFound = false; // no factor found yet;
repeat (x-2) {
factorFound = factorFound || ((x % i) == 0 );
// Remainder is 0 when x is divisible by i
i++;
}
if (factorFound) cout << x << " is not prime"
<< endl;
}
Conditional Expressions, Pitfalls
• condition?consequent : alternate
• int a; a=(b>10)?[(c=7)?2:3]:5
• if(d=5) versus if (d==5)
• If (0<b<2.5) versus If (0<b && b< 2.5)
Try these
• What is printed by this code snippet:
int x=3,y=1;
{
int x=4;
{
x = x+2;
}
y=x;
}
cout << (x+y);
}
Try these
• What does this code print?
int i=0,s=0;
repeat(3)
{
if (i%2==0)
s += i;
else s += 2*i;
i++;
}
cout << s;
Try these
What does this program print?
unsigned int x,c=0;
cin>>x;
repeat (32)
{
if (x%2==1)
c++;
x = x/2;
}
cout << c;