Week
#4
CS 161: Introduction to Computer Science
1
The switch Control Statement
•
Another C++ control statement is called the switch statement; it allows you to
pick the statements you want to execute from a list of possible statements,
instead of just two different alternatives (as is available with an if/else) or
a set of nested if/elses! It allows for multi-way decisions.
• A
switch statement looks like:
char grade;
cout <<"Enter the
grade..." <<endl;
cin >>grade;
switch (grade) {
case 'A': cout
<<"Excellent";
break;
case 'B': cout <<"Very
Good";
break;
case 'C': cout
<<"Passing";
break;
case 'D': case 'F': cout
<<"Too Bad";
break;
default :
cout <<"No match was
found...try again";
break;
}
cout
<<endl;
• C++
provides a "default" clause so that if there isn't a match something
is done. If the default is left off...and there is no match...no action takes
place at all.
• When
a case statement is executed, the value of Grade is checked and then depending
on which of the cases it matches -- the statement following the colon for that
case will be executed.
• To
exit from a switch statement...use break. Unlike Pascal, with C++ once you have
a match...it will fall thru (ignoring any additional case or default labels
that are encountered and continue executing code until a break is encountered.
• The
rule of thumb is that you can use these to switch on integers and characters.
It is not permitted to use the switch with floating point types or a string of
characters. The type of the expression following a switch keyword must be the
same as the expressions following each case keyword....and no two
expressions following the case keywords can be the same.
• You
can also use multiple statements for each case, without the need of {}; for
example:
char grade;
cout <<"Enter the
grade..." <<endl;
cin >>grade;
switch (grade) {
case 'A': cout
<<"Excellent";
cout <<endl <<"Keep up
the good work!";
break;
case 'B': cout <<"Very
Good";
break;
case 'C': cout
<<"Passing";
break;
case 'D':
case 'F': cout <<"Too
Bad";
break;
default :
cout <<"No match was
found...try again";
break;
}
cout
<<endl;
• case
<constant expression> is called a case
label.
• A
constant expression is an expression that involves only constants. Such
expressions may be evaluated during compilation rather than at runtime and may
be used in any place that a constant can occur.
• And,
you can even nest switch statements!
• To
understand all of this, some examples are necessary: First, let's show what
"fall thru" means:
# include <iostream>
using namespace std;
int main()
{
int count;
cout <<"Please enter the number of asterisks to
print\n";
cin >>count;
switch (count) { //
these parens are mandatory! // the {} pair surrounding the body is
also a must!
case 1: cout
<<"*";
case 2: cout
<<"**";
case 3: cout
<<"***";
case 4: cout
<<"****";
default: cout
<<"!";
}
cout <<endl;
return 0;
}
•
Guess what, fall thru means that if I entered "1"...that my output
would look like: "**********!" Incorrect.
• To take
care of this, we must add break statements. Notice that I don't need {} pairs
after each case...I can put in as many statements as I want after a case label.
int count;
cout <<"Please enter the number of asterisks to
print\n";
cin >>count;
switch (count) { //
these parens are mandatory! // the {} pair surrounding the body is
also a must!
case 1: cout
<<"*";
break;
case 2: cout
<<"**";
break;
case 3: cout
<<"***";
break;
case 4: cout
<<"****";
break;
default: cout
<<"!";
break;
}
cout <<endl;
• This
was the correct way to do things...but guess what, C++ does not require that
the body of a case be a compound statement or that the case/default labels
appear in any particular order. In fact, the following is the same program:
int count;
cout <<"Please enter the number of asterisks to
print\n";
cin >>count;
switch (count) { //
these parens are mandatory! // the {} pair surrounding the body is
also a must!
case 1: cout
<<"*";
break;
default: cout
<<"!"; //notice the
order...this produces
break; //the
same results!
case 3: cout
<<"***";
break;
case 2: cout
<<"**";
break;
case 4: cout
<<"****";
break;
}
cout <<endl;
• If
you ever intend to use the "fall thru" feature...I recommend that you
place a comment at the end of the case explicitly noting that the previous code
is intended to fall thru.
• So,
from all of this we know that we cannot use switch statements with real numbers
or with strings. And, switch statements are awkward when dealing with lists of
data where there are large-gaps in values.
Repetition in Programs
•
To really be able to write useful programs, we need the concept of looping.
Think about it for a minute. When you walk up to an ATM machine and insert your
card and punch in your code, a series of questions are asked. You can withdraw
money, deposit money, get your account balance, etc. After you do one function,
the machine asks if you want to do another function. If you say yes, it repeats
the process.
•
So far, we have been studying programs that have had limited use - because they
can do only do something once -- and can't repeat the process automatically
until the user says they are done. For example, the GradePoint Average program
only calculated the GPA for ONE student per execution and for only one term.
Not very versatile!
•
In reality, most programs include some action that needs to be repeated a
number of times. This process of repeating in C++ is called a loop. One way to
implement a loop is to use a while statement.
The while Statement
•
When implementing programs, we may not know how many times we want to loop. For
example, in our automatic bank teller program, we really don't know how many
times we will want to loop until the user presses the button that says they are
done.
•
To solve this we can use a while statement...this statement will loop until
some condition is met (like hitting the proper button!)
•
So, we could have implemented our teller
machine program as follows:
answer = 'Y'; //initialize your variable
while (answer == 'Y') {
cout <<" Enter
your selection on the keypad:";
cout <<" 1- Withdrawl, 2-Deposit,
3-Balance" <<endl;
cin >> selection;
.... put in
the code for withdrawl....and deposit....
if (selection == 3) {
cout
<<" Calculating your account balance..." <<endl;
cout
<<" The balance for " <<account <<" is "
cout
<<balance <<endl;
}
cout <<"Would
you like to continue?" <<endl;
cin >>answer;
} // The while loop ends here
cout <<"Thank you for
using UBANK ...";
cout <<"Please come
again" <<endl;
•
The while statement means that while
an expression is true, the body of the while loop will be executed. Once it is
no longer true, the body will be bypassed. The first thing that happens is that
the expression is checked, before the while loop is executed. THIS ORDER IS
IMPORTANT TO REMEMBER.
•
The Syntax of the While Loop is:
while (loop repetition condition)
<body>
Where, the <body> is either one
statement followed by a semicolon or a compound statement surrounded by {}. Remember the body is only executed
when the condition is true. Then, after
the body is executed, the condition is tested again...if it is still true, the
body is once again executed. The loop is not exited until the condition is retested
and found to be false.
•
Notice, you must remember to initialize the loop control variable before you
enter the while loop. Then, you must have some way of updating that variable
inside of the body of the loop so that it can change the condition from true to
false at some desired time. If this last step is missing, the loop will execute
"forever" ... this is called an infinite loop.
Infinite Loops
•
REMEMBER, you need to change one of the variables that is part of the
expression within the while loop; otherwise, you will have an infinite loop.
•
!= (not equal) signs should NEVER BE USED WHEN CHECKING THE VALUE OF REAL
NUMBERS, since it requires that the loop be terminated by checking if a number
has an exact value (for characters it is ok -- but remember the problem of
upper versus lower case!). With numbers it is better to use a <= or >= or
> or <
•
Let's look at a quick example:
This program prints the positive
even numbers less than 12
int x;
x= 2;
while (x != 12) {
cout <<x <<endl;
x = x + 2;
}
To print the odd numbers, you can't just
change the first line to x=1. Why?
Increment and Decrement
Operators
•
The ++ operator adds one and the -- operator subtracts one. Each
operator can be used in one of two forms:
prefix or postfix.
•
The ++ and -- operators are unary operators that can only be applied to
variables.
For example, the following increments the
variable i by one and
then decrements the variable i by one:
int i=0;
++i;
/* i is now equal to one; we could have achieved the
same result by writing i++ using the
postfix form;
it is the same as saying i=i+1; */
--i;
/* i is now equal to zero; we could have achieved the
same result by writing i--
using the postfix form;
it is the same as saying i=i-1; */
• Applying the ++ or -- operators not only
change the variable but also results in a value. This value can then be used in an expression.
But, BE CAREFUL! The resulting value
will be different depending on whether you use the prefix form or the postfix
form EVEN though the variable will end up with the same result in both cases!
• When you use the prefix form the meaning is
to modify the variable and THEN fetch its contents. The result in the variable and the value
resulting from applying the operator are the SAME.
++i; is
the same as i=i+1;
the
residual value of both is the incremented value of i
• When you use the postfix form the meaning is
to FIRST fetch the contents of the variable and THEN modify it. The result in the variable and the value
resulting from applying the operator are DIFFERENT!
• This means that i++; is not the same as
i=i+1;
since the residual value of i++ is the
original
value
of i before it is incremented!