Two
Simple Commands
So that meaningful examples can be developed in the next
chapter, it is necessary for you to understand, in their simplest
form, two C++ commands: the if and
the for. Later, these
commands will be explored completely.
The
if Statement
The C++ if
statement operates in much the same way that
an IF statement operates in any other language. Its simplest form is
if(condition)
statement;
where condition is
an expression that is evaluated to be either true or false. In C++,
true is non-zero and false is zero. If the condition is true, then
the statement will execute. If it is false, then the statement will
not execute. The following fragment displays the phrase 10
is less than 11 on the screen.
if(10 < 11) cout << "10 is less than 11";
The comparison operators, such as <
(less than) and >=
(greater than or equal), are
similar to those in other languages. However, in
C++, the equality operator is ==.
The following cout
statement will not execute, because the
condition of equality is false; that
is, because 10 is not equal to 11, the statement will not display
hello on
the screen.
if(10==11) cout << "hello"; Of
course, the operands inside an if
statement need not be constants. They can
also be variables, or even
calls to functions. The
following program shows an example of the if
statement. It prompts the user for
two numbers and reports if the first value is
less than the second. // This program illustrates
the if statement. #include <iostream> using namespace std; int
main()
{
int a, b;
cout
<< "Enter first number: ";
cin
>> a;
cout
<< "Enter second number: ";
cin
>> b;
if(a
< b) cout << "First number is less than second.";
return
0;
}
The for Loop
The for
loop repeats a statement a specified number
of times. The for loop
canoperate much like the FOR loop in other languages, including Java,
C#, Pascal, and BASIC. Its simplest form is for(initialization,
condition,
increment)
statement;
Here, initialization
sets a loop control variable to an initial
value. condition is
an expression that is tested each time the loop repeats. As long as
condition is
true (non-zero), the loop keeps running. The increment
is an expression that determines how the loop
control variable is incremented each time the loop repeats. For
example, the following program prints the numbers 1 through 100 on
the screen.
// A program that illustrates the for loop.
#include <iostream>
using namespace std;
int main()
{
int count;
for(count=1; count<=100; count=count+1)
cout << count << " ";
return 0;
}
Figure 2-1 illustrates the execution of the for
loop in this example. As you can see, count
is initialized to 1. Each time the loop
repeats, the condition count<=100 is
tested. If it is true, the value is output and count
is increased by one. When count
reaches a value greater than 100, the condition becomes false, and
the loop stops running.
In professionally written C++ code, you will seldom see
a statement like count=count+1,
because for this sort of statement, C++ supports a special shorthand
that looks like this: count++.
The ++ is
the increment operator.
It increases its operand by 1. The complement of ++
is –
–, the decrement
operator, which decreases its operand by 1.
For example, the preceding for
statement will
generally be written like this:
for(count=1;
count<=100; count++)
cout
<< count << " ";
This is the form that will be used throughout the rest
of this book.
Blocks
of Code
Because C++ is a structured (as well as an
object-oriented) language, it supports the creation of blocks of
code. A block is
a logically connected group of program statements that is treated as
a unit. In C++, a code block is created by placing a sequence of
statements between opening and closing curly braces. In this example,
if(x<10) {
cout << "too low, try again";
cin >> x;
}
the two statements after the if
and between the curly braces are both
executed only if x is
less than 10. These two statements, together with the braces,
represent a block of code. They are a logical unit: One of the
statements cannot execute without the other also executing. In C++,
the target of most commands can be either a single statement or a
code block. Code blocks allow many algorithms to be implemented with
greater clarity and efficiency. They can also help you better
conceptualize the true nature of an algorithm. The program that
follows uses a block of code. Enter and run the program so that you
can see the effect of the block.
// This program demonstrates a block of code.
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
if(a < b) {
cout << "First number is less than
second.\n";
cout << "Their difference is: " <<
b-a;
}
return
0;
}
This program prompts the user to enter two numbers from
the keyboard. If the first number is less than the second number,
then both cout statements
are executed. Otherwise, both are skipped. At no time can just one of
them execute.
Semicolons
and Positioning
In C++, the semicolon is a statement terminator.
That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.
As you know, a block is a set of logically connected statements that
are surrounded by opening and closing braces. A block is not
terminated with a semicolon. Since a block is
a group of statements, with a semicolon after each statement, it
makes sense that a block is not terminated by a semicolon; instead,
the end of the block is indicated by the closing brace. This is also
the reason that there is no semicolon following the closing brace of
a function. C++ does not recognize the end of the line as a
terminator. For this reason, it does not matter where on a line you
put a statement.
For example,
x = y;
y = y+1;
mul(x, y);
is the same as
x = y; y = y+1; mul(x, y);
to a C++ compiler.
Indentation
Practices
You may have noticed in the previous examples that
certain statements were indented. C++ is a free-form language,
meaning that it does not matter where you place statements relative
to each other on a line. However, over the years, a common and
accepted indentation style has developed that provides very readable
programs. This book follows that style, and it is recommended that
you do so as well. Using this style, you indent one level after each
opening brace, and move back out one level after each closing brace.
There are certain statements that encourage some additional
indenting; these will be covered later.
C++ Keywords
There are 63 keywords currently defined for Standard
C++. These are shown in Table 2-1. Together with the formal C++
syntax, they form the C++ programming language. Also, early versions
of C++ defined the overload keyword,
but it is now obsolete.
Keep in mind that the case of the keywords is
significant. C++ is a case-sensitive language, and it requires that
all keywords be in lowercase. For example, RETURN
will not be
recognized as the keyword return.
In C++ an identifier is
a name assigned to a function, a variable, or any other user-defined
item. Identifiers can be from one to several characters long. The
first 1024 characters will be significant. Variable names may start
with any letter of the alphabet or with an underscore. Next may be
either a letter, a digit, or an underscore. The underscore can be
used to enhance the readability of a variable name, as in first_name.
Uppercase and lowercase are different; that is, to C++, count
and COUNT are
separate names. Here are some examples of acceptable identifiers:
first last Addr1 top_of_file name23 _temp t s23e3 MyVar You cannot
use any of the C++ keywords as identifier names. Also, you should not
use the name of any standard function, such as abs,
for an identifier. Beyond these two restrictions, good programming
practice dictates that you use identifier names that reflect the
meaning or usage of the items being named.
The
Standard C++ Library
In the discussion of the sample programs earlier in this
chapter, it was mentioned that abs( ) is
provided with your C++ compiler. abs( ) is
not part of the C++ language per se, yet you will find it included
with every C++ compiler. This function, and many others, are found in
the standard library. We
will be making extensive use of library functions in the example
programs throughout this book. C++ defines a rather large set of
functions that will be contained in the standard library. These
functions are designed to perform many commonly needed tasks,
including I/O operations, mathematical computations, and string
handling. When you use a library function, the C++ compiler
automatically links the object code for that function to the object
code of your program. Because the C++ standard library is so large,
it already contains many of the functions that you will need to use
in your programs. The library functions act as building blocks that
you simply assemble. You should explore your compiler’s library
documentation. You may be surprised at how varied the library
functions are. If you write a function that you will use again and
again, it too can be stored in a library. In addition to providing
library functions, every C++ compiler also contains a class
library, which is an
object-oriented library. Finally, C++ defines the Standard Template
Library (STL), which provides reusable routines that can be
configured to meet your specific requirements. However, you will need
to wait until you learn about classes,
objects, and templates before you can make use of the
class library or the STL.
CHAPTER
4
Program
Control Statements
In execution. There are three specific categories of
program control statements: selection
statements, which include the if
and the switch;
iteration statements,
which include the for,
while, and do-while
loops; and jump
statements, which include break,
continue, return,
and goto. (However, a
discussion of the return statement
is deferred until
later in this book.) This
chapter begins with a thorough examination of the if
and for statements. It then discusses the
other program control statements.
The
if Statement
Chapter 2 introduced the if
statement. Now it is time to examine it in
detail. The complete form of the if statement
is
if(expression)
statement;
else statement;
where the targets of the if and
else are single
statements. The else clause
is optional.
The targets of both the if and
else can be blocks of
statements. The general form of
the if using
blocks of statements is
if(expression)
{
statement sequence
}
else
{
statement
sequence
}
If the conditional expression is true, the target of the
if will be executed;
otherwise, if it exists, the target of the else
will be executed. At no time will both of
them be executed. The conditional expression controlling the if
may be any type of valid C++ expression that
produces a true or false result. The following program demonstrates
the if by playing a
simple version of the "guess the magic number" game. The
program generates a random number, prompts for your guess, and prints
the message ** Right ** if
you guess the magic number. This program also introduces another
standard C++ library function, called rand( ),
which returns a randomly selected integer value. It requires the
header called <cstdlib>.
// Magic Number program.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int magic; // magic number
int guess; // user's guess
magic = rand(); // get a random number
cout << "Enter your guess: ";
cin >> guess;
if(guess == magic) cout << "** Right **";
return 0;
}
This program uses the relational operator ==
to determine whether the guess matches the
magic number. If it does, the message is printed on the screen.
Taking the Magic Number program further, the next version uses the
else to print a
message when the wrong number is picked.
// Magic Number program: 1st improvement.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int magic; // magic number
int guess; // user's guess
magic = rand(); // get a random number
cout << "Enter your guess: ";
cin >> guess;
if(guess == magic) cout << "** Right **";
else cout << "...Sorry, you're wrong.";
return 0;
}
The
Conditional Expression
Sometimes newcomers to C++ are confused by the fact that
any valid C++ expression can be used to control the if.
That is, the type of expression need not be restricted to only those
involving the relational and logical operators or to operands of type
bool. All that is
required is that the controlling expression evaluate to either a true
or false result. As you should recall from the previous chapter, a
value of zero is automatically converted into false,
and all non-zero values are converted to true.
Thus, any expression that results in a zero or non-zero value can be
used to control the if.
For example, the following program reads two integers from the
keyboard and displays the quotient. In order to avoid a
divide-by-zero error, an if statement,
controlled by the second number, is used.
//
Divide the first number by the second.
#include
<iostream>
using
namespace std;
int
main()
{
int
a, b;
cout
<< "Enter two numbers: ";
cin
>> a >> b;
if(b)
cout << a/b << '\n';
else
cout << "Cannot divide by zero.\n";
return
0;
}
Notice that b (the
divisor) is tested for zero by using if(b).
This approach works because when b is
zero, the condition controlling the if is
false and the else executes.
Otherwise, the condition is true (non-zero) and the division takes
place. It is not necessary (and would be considered bad style by most
C++ programmers) to write this if as
shown here:
if(b
!= 0) cout << a/b << '\n';
This form of the statement is redundant and potentially
inefficient.
Nested
ifs
A nested if
is an if statement
that is the target of another if or
an else. Nested ifs
are very common in programming. The main thing to remember about
nested ifs in C++ is
that an else statement
always refers to the nearest if statement
that is within the same block as the else and
not already associated with an else.
Here is an example:
If
(i) {
if(j)
statement1;
if(k)
statement2; // this if
else
statement3; // is associated with this else
}
else
statement4; // associated with if(i)
As the comments indicate, the final else
is not associated with if(j)
(even though it is the closest if
without an else),
because it is not in the same block. Rather, the final else
is associated with if(i).
The inner else is
associated with if(k) because
that is the nearest if.
C++ allows at least 256 levels of nesting. In practice, you will
seldom need to nest if
statements this deeply.
We can use a nested if to
add a further improvement to the Magic Number program. This addition
provides the player with feedback about a wrong guess.
//
Magic Number program: 2nd improvement.
#include
<iostream>
#include
<cstdlib>
using
namespace std;
int
main()
{
int
magic; // magic number
int
guess; // user's guess
magic
= rand(); // get a random number
cout
<< "Enter your guess: ";
cin
>> guess;
if
(guess == magic) {
cout
<< "** Right **\n";
cout
<< magic << " is the magic number.\n";
}
else
{
cout
<< "...Sorry, you're wrong.";
//
use a nested if statement
if(guess
> magic)
cout
<<" Your guess is too high.\n";
else
cout
<< " Your guess is too low.\n";
}
return
0;
}
The
if-else-if Ladder
A common programming construct that is based upon nested
ifs is the if-else-if
ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
The conditional expressions are evaluated from the top
downward. As soon as a true condition is found, the statement
associated with it is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else
statement will be executed. The final else
often acts as a default condition; that is,
if all other conditional tests fail, then the last else
statement is performed. If there is no final
else and all other
conditions are false, then no action will take place.
The following program demonstrates the if-else-if
ladder.
//
Demonstrate an if-else-if ladder.
#include
<iostream>
using
namespace std;
int
main()
{
int
x;
for(x=0;
x<6; x++) {
if(x==1)
cout << "x is one\n";
else
if(x==2) cout << "x is two\n";
else
if(x==3) cout << "x is three\n";
else
if(x==4) cout << "x is four\n";
else
cout << "x is not between 1 and 4\n";
}
return
0;
}
The program produces the following output:
x
is not between 1 and 4
x
is one
x
is two
x
is three
x
is four
x
is not between 1 and 4
As you can see, the default else
is executed only if none of the preceding if
Statements succeed.
The
switch Statement
Before looking at C++’s other loop constructs, let’s
examine its other selection statement:
the switch.
Although a series of nested if statements
can perform multiway tests, for many situations, a more efficient
approach can be used. C++ has a built-in multiple branch decision
statement called switch.
It works like this: the value of an expression is successively tested
against a list of integer or character constants. When a match is
found, the statement sequence associated with that match is executed.
The general form of the switch statement
is switch(expression)
{
case constant1:
statement
sequence
break;
case constant2:
statement
sequence
break;
case constant3:
statement
sequence
break;
.
.
.
default:
statement
sequence
}
switch
is C++’s
multiway
decision
statement.
The switch expression
must evaluate to either a character or an integer value.
(Floating-point expressions, for example, are not allowed.)
Frequently, the expression controlling the switch
is simply a variable. The default
statement sequence is performed if no matches
are found. The default is
optional; if it is not present, no action takes place if all matches
fail. When a match is found, the statements associated with that case
are executed until the break
is encountered or, in the case of the default
or the last case,
the end of the switch
is reached. There are four important things to know about the switch
statement:
Ÿ The switch
differs from the if in
that switch can test
only for equality (i.e., for matches between the switch
expression and the case
constants), whereas the if
conditional expression can be of any type.
Ÿ No two case
constants in the same switch
can have identical values. Of course, a
switch statement
enclosed by an outer switch may
have case constants in
common.
Ÿ A switch
statement is usually more efficient than
nested ifs.
Ÿ The statement sequences
associated with each case are
not blocks. However,
the entire switch statement
does define a block.
The importance of this will become apparent as you learn more about
C++.
Standard C++ specifies that a switch
can have at least 16,384 case
statements. In practice, you will want to
limit the number of case statements
to a much smaller total, for reasons of efficiency. The following
program demonstrates the switch.
It creates a simple "help" system that describes the
meaning of the for,
if, and switch
statements. It displays the help topics and
then waits for the user to enter his or her choice. This choice is
then used by the switch to
display information about the requested topic. (You might find it fun
to expand the information in this program. You can also add new
topics as you learn about them.)
// Demonstrate the switch using a simple "help"
program.
#include <iostream>
using namespace std;
int main()
{
int choice;
cout << "Help on:\n\n";
cout << "1. for\n";
cout << "2. if\n";
cout << "3. switch\n\n";
cout << "Enter choice (1-3): ";
cin >> choice;
cout << "\n";
switch(choice) {
case 1:
cout << "for is C++'s most versatile
loop.\n";
break;
case 2:
cout << "if is C++'s conditional branch
statement.\n";
break;
case 3:
cout << "switch is C++'s multiway branch
statement.\n";
break;
default:
cout
<< "You must enter a number between 1 and 3.\n";
}
return
0;
}
Here is a sample run:
Help
on:
1.
for
2.
if
3.
switch
Enter
choice (1-3): 2
if
is C++'s conditional branch statement.
Technically, the break statement
is optional, although most applications of the switch
will use it. When encountered within the
statement sequence of a case,
the break statement
causes program flow to exit from the entire switch
statement and resume at the next statement
outside the switch.
However, if a break statement
does not end the statement sequence associated with a case,
then all the statements at and below the
matching case will be
executed until a break (or
the end of the switch)
is encountered.
For example, study the following program carefully. Can
you figure out what it will display on the screen?
#include
<iostream>
using
namespace std;
int
main()
{
int
i;
for(i=0;
i<5; i++) {
switch(i)
{
case
0: cout << "less than 1\n";
case
1: cout << "less than 2\n";
case
2: cout << "less than 3\n";
case
3: cout << "less than 4\n";
case
4: cout << "less than 5\n";
}
cout
<< '\n';
}
return
0;
}
This program displays the following output:
less
than 1
less
than 2
less
than 3
less
than 4
less
than 5
less
than 2
less
than 3
less
than 4
less
than 5
less
than 3
less
than 4
less
than 5
less
than 4
less
than 5
less
than 5
As this program illustrates, execution will continue
into the next case if
no break statement
is present.
You can have empty cases,
as shown in this example:
switch(i)
{
case
1:
case
2:
case
3: do_something();
break;
case
4: do_something_else();
break;
In this fragment, if i has
the value 1, 2, or 3, then do_something( ) is
called. If i has the
value 4, then do_something_else( ) is
called. The "stacking" of cases,
as shown in this example, is very common when several cases
share common code.
Nested
switch Statements
It is possible to have a switch
as part of the statement sequence of an outer
switch. Even if the
case constants of the
inner and outer switch contain
common values, no conflicts will arise. For example, the following
code fragment is perfectly acceptable:
switch(ch1) {
case 'A': cout << "This A is part of outer
switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
C++ specifies that at least 256 levels of nesting be
allowed for switch statements.
Frankly, few programs ever require anywhere near 256 levels of
nesting.
LOOPS in c++
Loops allow programmers to repeat one or more statements
a bunch of times. There are three main kinds of loops: for loops,
while loops, and do loops.
FOR LOOPS
for (<initialization>; <stopping
condition>;
<expression) {
<one or more statements>
} //end for
<expression) {
<one or more statements>
} //end for
The <initialization>
portion is often used to set the value of a counter variable. The
<expression> is
typically used to increment the counter variable. The for loop
continues executing the statements it contains until the <stopping
condition> is met. The <stopping
condition> may be a boolean expression which
evaluates to true or false, or it actually may be an expression which
produces any value. In the latter case, this value is converted to an
integer. If this integer is 0, then the <stopping
condition> is considered to be false. If this
integer is not 0, the <stopping condition>
is considered to be true.
For example,
int count, num,
total = 0;
for (count = 1; count <= 10; count++) {
cout << "Enter integer #" << count << ": ";
cin >> num;
total = total + num;
} //end for
for (count = 1; count <= 10; count++) {
cout << "Enter integer #" << count << ": ";
cin >> num;
total = total + num;
} //end for
Note: The "++" operator adds one to a number,
so count++; is equivalent to count = count + 1
WHILE LOOPS
while (<stopping
condition>) {
<one or more statements>
} end while
<one or more statements>
} end while
The while loop checks to see if the <stopping
condition> is true (or not -). If so, the
statements inside the while loop are executed, then the <stopping
condition> is checked again, and so on. When
the <stopping condition>
is found to be false (or -), execution continues with whatever
statements follow at the end of the while loop.
For example,
int total = 0, num = 999;
while (num != 0) {
cin >> num;
total = total + num;
}
while (num != 0) {
cin >> num;
total = total + num;
}
DO LOOP
do {
<one or more statements>
} while (<stopping condition>)
<one or more statements>
} while (<stopping condition>)
The do loop is similar to the while loop, except that it
checks the <stopping condition>
after the statements that it contains. This means that the statements
inside a do loop are always executed at least once, whereas the
statements inside a while loop may never be executed.
No comments:
Post a Comment