Chapter 7Switching PathsIn This Chapter▶ Using the switch keyword to choose between multiple paths▶ Taking a default path▶ Falling through from one case to anotherOften programs have to decide between a very limited number of options: Either m is greater than n or it’s not; either the lug nut is present or it’s not. Sometimes, however, a program has to decide between a largenumber of possible legal inputs. This could be handled by a series of ifstatements, each of which tests for one of the legal inputs. However, C++ provides a more convenient control mechanism for selecting among a number ofoptions known as the switch statement.Controlling Flow with
the switch StatementThe switch statement has the following format:switch(expression){
case const1:
// go here if expression == const1
break;
case const2:
// go here if expression == const2
break;
case const3: // repeat as often as you like
// go here if expression == const3
break;
default:
// go here if none of the other cases match
}
82 Part II: Writing a Program: Decisions, DecisionsUpon encountering the switch statement, C++ evaluates expression. Itthen passes control to the case with the same value as expression. Controlcontinues from there to the break statement. The break transfers control tothe } at the end of the switch statement. If none of the cases match, controlpasses to the default case.
The default case is optional. If the expression doesn’t match any case and no
default case is provided, control passes immediately to the }.Consider the following example code snippet:int nMonth;cout << “Enter the number of the month: “;
cin >> nMonth;
switch (nMonth)
{
case 1:
cout << “It’s January” << endl;
break;
case 2:
cout << “It’s February” << endl;;
break;
case 3:
cout << “It’s March” << endl;;
break;
case 4:
cout << “It’s April” << endl;;
break;
case 5:
cout << “It’s May” << endl;;
break;
case 6:
cout << “It’s June” << endl;;
break;
case 7:
cout << “It’s July” << endl;;
break;
case 8:
cout << “It’s August” << endl;;
break;
case 9:
cout << “It’s September”<< endl;;
break;
case 10:
cout << “It’s October” << endl;;
break;
case 11:
cout << “It’s November” << endl;;
break;
Chapter 7: Switching Paths 83case 12:cout << “It’s December” << endl;;
break;
default:
cout << “That’s not a valid month” << endl;;
}I got the following output from the program when inputting a value of 3:Enter the number of the month: 3It’s March
Press any key to continue . . .Figure 7-1 shows how control flowed through the switch statement to generate the earlier result of “March.”Figure 7-1:Flowthrough aswitchstatementlisting the
months of
the year
where the
operator
enters
month 3.int nMonth;cout << “Enter the number of the month: ”;
cin >> nMonth;
switch (nMonth)
{
case 1:
cout << “It’s January” << end1;;
break;
case 2:
cout << “It’s February” << end1;;
break;
case 3:
cout << “It’s March” << end1;;
break;
case 4:
cout << “It’s April” << end1;;
break;
case 5:
cout << “It’s January” << end1;
break;
case 12:
cout << “It’s December” << end1;;
break;
default:
cout << “That’s not a valid month” << end1;;
}For nMonth = 384 Part II: Writing a Program: Decisions, DecisionsA switch statement is not like a series of if statements. For example, onlyconstants are allowed after the case keyword (or expressions that can becompletely evaluated at build time). You cannot supply an expression after a
case. Thus, the following is not legal:// cases cannot be expressions; in general, the// following is not legal
switch(n)
{
case m:
cout << “n is equal to m” << endl;
break;
case 2 * m:
cout << “n is equal to 2m” << endl;
break;
case 3 * m:
cout << “n is equal to 3m” << endl;
}Each of the cases must have a value at build time. The value of m is notknown until the program executes.Control Fell Through: Did I break It?Just as the default case is optional, the break at the end of each case is alsooptional. Without the break statement, however, control simply continueson from one case to the next. Programmers say that control falls through.This is most useful when two or more cases are handled in the same way.
For example, C++ may differentiate between upper- and lowercase, but most
humans do not. The following code snippet prompts the user to enter a C to
create a checking account and an S to create a savings account. However, by
providing extra case statements, the snippet handles lowercase c and s the
same way:cout << “Enter C to create checking account, “<< “S to create a saving account, “
<< “and X to exit: “;
cin >> cAccountType;
switch(cAccountType)
{
case ‘S’: // upper case S
case ‘s’: // lower case s
// creating savings account
break;
case ‘C’: // upper case C
case ‘c’: // lower case c
Chapter 7: Switching Paths 85// create checking accountbreak;
case ‘X’: // upper case X
case ‘x’: // lower case x
// exit code goes here
break;
default:
cout << “I didn’t understand that” << endl;
}Implementing an Example Calculator
with the switch StatementThe following SwitchCalculator program uses the switch statement to implement a simple calculator:// SwitchCalculator - use the switch statement to// implement a calculator
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter operand1 op operand2
int nOperand1;
int nOperand2;
char cOperator;
cout << “Enter ‘value1 op value2’\n”
<< “where op is +, -, *, / or %:” << endl;
cin >> nOperand1 >> cOperator >> nOperand2;
// echo what the operator entered
cout << nOperand1 << “ “
<< cOperator << “ “
<< nOperand2 << “ = “;
// now calculate the result; remember that the
// user might enter something unexpected
switch (cOperator)
{
86 Part II: Writing a Program: Decisions, Decisionscase ‘+’:cout << nOperand1 + nOperand2;
break;
case ‘-’:
cout << nOperand1 - nOperand2;
break;
case ‘*’:
case ‘x’:
case ‘X’:
cout << nOperand1 * nOperand2;
break;
case ‘/’:
cout << nOperand1 / nOperand2;
break;
case ‘%’:
cout << nOperand1 % nOperand2;
break;
default:
// didn’t understand the operator
cout << “ is not understood”;
}
cout << endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}This program begins by prompting the user to enter “value1 op value2”where op is one of the common arithmetic operators +, -, *, / or %. The program then reads the variables nOperand1, cOperator, and nOperand2.The program starts by echoing back to the user what it read from the keyboard. It follows this with the result of the calculation.
Echoing the input back to the user is always a good programming practice. It
gives the user confirmation that the program read his input correctly.
The switch on cOperator differentiates between the operations that thiscalculator implements. For example, in the case that cOperator is ‘+’, theprogram reports the sum of nOperand1 and nOperand2.Because ‘X’ is another common symbol for multiply, the program accepts‘*’, ‘X’, and ‘x’ all as synonyms for multiply using the case “fall through”feature. The program outputs an error message if cOperator doesn’t matchany of the known operators.
Chapter 7: Switching Paths 87The output from a few sample runs appears as follows:Enter ‘value1 op value2’where op is +, -, *, / or %:22 x 622 x 6 = 132Press any key to continue . . .
Enter ‘value1 op value2’
where op is +, -, *, / or %:22 / 622 / 6 = 3Press any key to continue . . .
Enter ‘value1 op value2’
where op is +, -, *, / or %:22 % 622 % 6 = 4Press any key to continue . . .
Enter ‘value1 op value2’
where op is +, -, *, / or %:22 $ 622 $ 6 = is not understoodPress any key to continue . . .Notice that the final run executes the default case of the switch statementsince the character ‘$’ did not match any of the cases.88 Part II: Writing a Program: Decisions, Decisions
Monday, 5 November 2018
if in dev c++
Chapter 6if I Could Make My Own DecisionsIn This Chapter▶ Defining character variables and constants▶ Encoding characters▶ Declaring a string▶ Outputting characters to the consoleMaking decisions is a part of the everyday world. Should I get a drink now or wait for the commercial? Should I take this highway exit to goto the bathroom or else wait for the next? Should I take another step or stop
and smell the roses? If I am hungry or I need gas, then I should stop at the
convenience store. If it is a weekend and I feel like it, then I can sleep in. See
what I mean?
An assistant, even a stupid one, has to be able to make at least rudimentary
decisions. Consider the Tire Changing Language in Chapter 1. Even there, the
program had to be able to test for the presence of a lug nut to avoid waving a
wrench around uselessly in space over an empty bolt, thereby wasting everyone’s time.
All computer languages provide some type of decision-making capability. In
C++, this is handled primarily by the if statement.The if StatementThe format of the if statement is straightforward:if (m > n) // if m is greater than n...{
// ...then do this stuff
}
70 Part II: Writing a Program: Decisions, DecisionsWhen encountering if, C++ first executes the logical expression containedwithin the parentheses. In this case, the program evaluates the conditional
expression “is m greater than n.” If the expression is true, that is, if m truly isgreater than n, then control passes to the first statement after the { and continues from there. If the logical expression is not true, control passes to thefirst statement after the }.Comparison operatorsTable 6-1 shows the different operators that can be used to compare valuesin logical expressions.
Binary operators have the format expr1 operator expr2.Table 6-1 The Comparison OperatorsOperator Meaning== equality; true if the left-hand argument has the same value as theexpression on the right!= inequality; opposite of equality> greater than; true if the left-hand argument is greater than the right< less than; true if the left-hand argument is less than the right>= greater than or equal to; true if the left argument is greater than orequal to the right<= less than or equal to; true if the left argument is less than or equal tothe rightDon’t confuse the equality operator (==) with the assignment operator (=).This is a common mistake for beginners.
The following BranchDemo program shows how the operators shown in
Table 6-1 are used:// BranchDemo - demonstrate the if statement#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
Chapter 6: if I Could Make My Own Decisions 71{// enter operand1 and operand2
int nOperand1;
int nOperand2;
cout << “Enter argument 1:”;
cin >> nOperand1;
cout << “Enter argument 2:”;
cin >> nOperand2;
// now print the results
if (nOperand1 > nOperand2)
{
cout << “Argument 1 is greater than argument 2”
<< endl;
}
if (nOperand1 < nOperand2)
{
cout << “Argument 1 is less than argument 2”
<< endl;
}
if (nOperand1 == nOperand2)
{
cout << “Argument 1 is equal to argument 2”
<< endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}Program execution begins with main() as always. The program first declarestwo int variables cleverly named nOperand1 and nOperand2. It thenprompts the user to “Enter argument 1”, which it reads into nOperand1.The process is repeated for nOperand2.The program then executes a sequence of three comparisons. It first checks
whether nOperand1 is less than nOperand2. If so, the program outputs thenotification “Argument 1 is less than argument 2”. The second ifstatement displays a message if the two operands are equal in value. Thefinal comparison is true if nOperand1 is greater than nOperand2.The following shows a sample run of the BranchDemo program:Enter argument 1:5Enter argument 2:10Argument 1 is less than argument 2Press any key to continue . . .
72 Part II: Writing a Program: Decisions, DecisionsFigure 6-1 shows the flow of control graphically for this particular run.Figure 6-1:The path
taken by the
BranchDemo
program
when the
user enters
5 for the first
argument
and 10 for
the second.// enter operand1 and operand2int nOperand1;
int nOperand2;
cout << "Enter argument 1:";
cin >> nOperand1;
cout << "Enter argument 2:";
cin >> nOperand2;
// now print the results
if (nOperand1 > nOperand2)
{
cout << "Argument 1 is greater than argument 2"cout << end1;}
if (nOperand1 < nOperand2)
{
cout << "Argument 1 is less than argument 2"cout << end1;}
if (nOperand1 == nOperand2)
{
cout << "Argument 1 is equal to argument 2"cout << end1;}Entered 5
Entered 10
5 > 10 is false
5 < 10 is true
5 == 10 is falseThe way the BranchDemo program is written, all three comparisons are performed every time. This is slightly wasteful since the three conditions aremutually exclusive. For example, nOperand1 > nOperand2 can’t possiblybe true if nOperand1 < nOperand2 has already been found to be true.Later in this chapter, I show you how to avoid this waste.Say “No” to “No braces”Actually the braces are optional. Without braces, only the first expressionafter the if statement is conditional. However, it is much too easy to make amistake this way, as demonstrated in the following snippet:// Can’t have a negative age. If age is less than zero...if (nAge < 0)
cout << “Age can’t be negative; using 0” << endl;
nAge = 0;
// program continues
Chapter 6: if I Could Make My Own Decisions 73You may think that if nAge is less than 0, this program snippet outputs a message and resets nAge to zero. In fact, the program sets nAge to zero no matterwhat its original value. The preceding snippet is equivalent to the following:// Can’t have a negative age. If age is less than zero...if (nAge < 0)
{
cout << “Age can’t be negative; using 0” << endl;
}
nAge = 0;
// program continuesIt’s clear from the comments and the indent that the programmer reallymeant the following:// Can’t have a negative age. If age is less than zero...if (nAge < 0)
{
cout << “Age can’t be negative; using 0” << endl;
nAge = 0;
}
// program continuesThe C++ compiler can’t catch this type of mistake. It’s safer just to alwayssupply the braces.
C++ treats all white space the same. It ignores the alignment of expressions on
the page.
Always use braces to enclose the statements after an if statement, even ifthere is only one. You’ll generate a lot fewer errors that way.What else Is There?C++ allows the program to specify a clause after the keyword else that isexecuted if the conditional expression is false, as in the following example:if (m > n) // if m is greater than n...{
// ...then do this stuff;...
}
else // ...otherwise,...
{
// ...do this stuff
}
74 Part II: Writing a Program: Decisions, DecisionsThe else clause must appear immediately after the close brace of the ifclause. In use, the else appears as shown in the following snippet:if (nAge < 0){
cout << “Age can’t be negative; using 0.” << endl;
nAge = 0;
}
else
{
cout << “Age of “ << nAge << “ entered” << endl;
}In this case, if nAge is less than zero, the program outputs the message “Agecan’t be negative; using 0.” and then sets nAge to 0. This corresponds to the flow of control shown in the first image in Figure 6-2. If nAge isnot less than zero, the program outputs the message “Age of x entered”,where x is the value of nAge. This is shown in the second image in Figure 6-2.Figure 6-2:Flow of control through
an if andelse for
two different values
of nAge.if (nAge < 0){
cout << "Age can’t be negative; using 0."
<< end1;
nAge = 0;
}
else
{
cout << "Age of " << nAge
<< " entered" << end1;
}For nAge = –1if (nAge < 0){
cout << "Age can’t be negative; using 0."
<< end1;
nAge = 0;
}
else
{
cout << "Age of " << nAge
<< " entered" << end1;
}For nAge = 26
Chapter 6: if I Could Make My Own Decisions 75
Nesting if StatementsThe braces of an if or an else clause can contain another if statement.These are known as nested if statements. The following NestedIf programshows an example of a nested if statement in use.// NestedIf - demonstrate a nested if statement//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{Logical expressions: Do they have any value?At the beginning of this chapter, I called the comparison symbols < and > operators, and I describedstatements containing these operators as expressions. But expressions have a value and a type.What is the value and type of an expression like m > n? In C++, the type of this expression is bool(named in honor of George Boole, the inventor of Logic Calculus). Expressions of type bool canhave only one of two values: true or else false. Thus, you can write the following:bool bComparison = m > n;For historical reasons, there is a conversion between the numerical types like int and char andbool: A value of 0 is considered the same as false. Any non-zero value is considered the sameas true.Thus, the if statementif (cCharacter){
// execute this code if cCharacter is not NULL
}is the same asif (cCharacter != ‘\0’){
// execute this code if cCharacter is not NULL
}Assigning a true/false value to a character may seem a bit obtuse, but you’ll see in Chapter 16 thatit has a very useful application.
76 Part II: Writing a Program: Decisions, Decisions// enter your birth yearint nYear;
cout << “Enter your birth year: “;
cin >> nYear;
// Make determination of century
if (nYear > 2000)
{
cout << “You were born in the 21st century”
<< endl;
}
else
{
cout << “You were born in “;
if (nYear < 1950)
{
cout << “the first half”;
}
else
{
cout << “the second half”;
}
cout << “ of the 20th century”
<< endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}This program starts by asking the user for his birth year. If the birth year isgreater than 2000, then the program outputs the string “You were born inthe 21st century”.The year 2000 belongs to the 20th century, not the 21st.
If the birth year is not greater than 2000, then the program enters the elseclause of the outer if statement. This clause starts by outputting the string“You were born in” before comparing the birth year to 1950. If the birthyear is less than 1950, then the program adds the first “the first half”.If the birth year is not less than 1950, then the else clause of the inner ifstatement is executed, which tacks on the phrase “the second half”.Finally, the program adds the concluding phrase “of the 20th century”to whatever has been output so far.Chapter 6: if I Could Make My Own Decisions 77In practice, the output of the program appears as follows for three possiblevalues for birth year. First, 2002 produces the following:Enter your birth year: 2002You were born in the 21st centuryPress any key to continue . . .My own birth year of 1956 generates the following:Enter your birth year: 1956You were born in the second half of the 20th century
Press any key to continue . . .Finally, my father’s birth year of 1932 generates the third possibility:Enter your birth year: 1932You were born in the first half of the 20th century
Press any key to continue . . .I could use a nested if to avoid the unnecessary comparisons in theNestedBranchDemo program:if (nOperand1 > nOperand2){
cout << “Argument 1 is greater than argument 2”
<< endl;
}
else
{
if (nOperand1 < nOperand2)
{
cout << “Argument 1 is less than argument 2”
<< endl;
}
else
{
cout << “Argument 1 is equal to argument 2”
<< endl;
}
}This version performs the first comparison just as before. If nOperand1 isgreater than nOperand2, this snippet outputs the string “Argument 1 isgreater than argument 2”. From here, however, control jumps to thefinal closed brace, thereby skipping the remaining comparisons.
78 Part II: Writing a Program: Decisions, DecisionsIf nOperand1 is not greater than nOperand2, then the snippet performs asecond test to differentiate the case that nOperand1 is less than nOperand2from the case that they are equal in value.Figure 6-3 shows graphically the flow of control for the NestedBranchDemo
program for the same input of 5 and 10 described earlier in the chapter.Figure 6-3:The path
taken by the
NestedBranchDemo
program
when the
user enters
5 and 10
as before.// enter operand1 and operand2int nOperand1;
int nOperand2;
cout << "Enter argument 1:";
cin >> nOperand1;
cout << "Enter argument 2:";
cin >> nOperand2;
// now print the results
if (nOperand1 > nOperand2)
{
cout << "Argument 1 is greater than argument 2"
<< end1;
}
else
{
cout << "Argument 1 is less than argument 2"cout << end1;}
else
{
cout << "Argument 1 is equal to argument 2"cout << end1;}
}Entered 5
Entered 10
5 > 10 is falsePerforming the test for equality is unnecessary: If nOperand1 is neithergreater than nor less than nOperand2, then it must be equal.Compound Conditional ExpressionsThe three logical operators that can be used to create what are known ascompound conditional expressions are shown in Table 6-2.Chapter 6: if I Could Make My Own Decisions 79Table 6-2 The Logical OperatorsOperator Meaning&& AND; true if the left- and right-hand arguments are true; otherwise, false|| OR; true if either the left- or right-hand arguments is true; otherwise, false
! NOT; true if the argument on the right is false; otherwise, falseThe programmer is asking two or more questions in a conditional compoundexpression, as in the following code snippet:// make sure that nArgument is between 0 and 5if (0 < nArgument && nArgument < 5)Figure 6-4 shows how three different values of nArgument are evaluated bythis expression.Figure 6-4:The evaluation of the
compound
expression0 < n&& n <
5 for three
different
values of n.
0 < nArgument && nArgument < 5
where nArgument = –1
0 < –1 && –1 < 5
false && true
false
where nArgument = 7
0 < 7 && 7 < 5
true&&false
false
where nArgument = 2
0 <2 && 2 < 5
true && true
trueBy the way, the snippetif (m < nArgument && nArgument < n)is the normal way of coding the expression “if nArgument is betweenm and n, exclusive”. This type of test does not include the end points —that is, this test will fail if nArgument is equal to m or n. Use the <= comparison operator if you want to include the end points.80 Part II: Writing a Program: Decisions, DecisionsShort circuit evaluationLook carefully at a compound expression involving a logical AND likeif (expr1 && expr2)If expr1 is false, then the overall result of the compound expression is false, irrespective ofthe value of expr2. In fact, C++ doesn’t even evaluate expr2 if expr1 is false — false &&anything is false. This is known as short circuit evaluation because it short circuits aroundexecuting unnecessary code in order to save time.
The situation is exactly the opposite for the logical OR:if (expr1 || expr2)If expr1 is true, then the overall expression is true, irrespective of the value of expr2.Short circuit evaluation is a good thing since the resulting programs execute more quickly;
however, it can lead to unexpected results in a few cases. Consider the following admittedly contrived case:if (m <= nArgument && nArgument++ <= n)The intent is to test whether nArgument falls into the range [m, n] and to incrementnArgument as part of the test. However, short circuit evaluation means that the second testdoesn’t get executed if m <= nArgument is not true. If the second test is never evaluated,then nArgument doesn’t get incremented.Remember: If you didn’t follow that, just remember the following: Don’t put an expression that hasa side effect like incrementing a variable in a conditional.
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-3147778191066425",
enable_page_level_ads: true
});
</script>
and smell the roses? If I am hungry or I need gas, then I should stop at the
convenience store. If it is a weekend and I feel like it, then I can sleep in. See
what I mean?
An assistant, even a stupid one, has to be able to make at least rudimentary
decisions. Consider the Tire Changing Language in Chapter 1. Even there, the
program had to be able to test for the presence of a lug nut to avoid waving a
wrench around uselessly in space over an empty bolt, thereby wasting everyone’s time.
All computer languages provide some type of decision-making capability. In
C++, this is handled primarily by the if statement.The if StatementThe format of the if statement is straightforward:if (m > n) // if m is greater than n...{
// ...then do this stuff
}
70 Part II: Writing a Program: Decisions, DecisionsWhen encountering if, C++ first executes the logical expression containedwithin the parentheses. In this case, the program evaluates the conditional
expression “is m greater than n.” If the expression is true, that is, if m truly isgreater than n, then control passes to the first statement after the { and continues from there. If the logical expression is not true, control passes to thefirst statement after the }.Comparison operatorsTable 6-1 shows the different operators that can be used to compare valuesin logical expressions.
Binary operators have the format expr1 operator expr2.Table 6-1 The Comparison OperatorsOperator Meaning== equality; true if the left-hand argument has the same value as theexpression on the right!= inequality; opposite of equality> greater than; true if the left-hand argument is greater than the right< less than; true if the left-hand argument is less than the right>= greater than or equal to; true if the left argument is greater than orequal to the right<= less than or equal to; true if the left argument is less than or equal tothe rightDon’t confuse the equality operator (==) with the assignment operator (=).This is a common mistake for beginners.
The following BranchDemo program shows how the operators shown in
Table 6-1 are used:// BranchDemo - demonstrate the if statement#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
Chapter 6: if I Could Make My Own Decisions 71{// enter operand1 and operand2
int nOperand1;
int nOperand2;
cout << “Enter argument 1:”;
cin >> nOperand1;
cout << “Enter argument 2:”;
cin >> nOperand2;
// now print the results
if (nOperand1 > nOperand2)
{
cout << “Argument 1 is greater than argument 2”
<< endl;
}
if (nOperand1 < nOperand2)
{
cout << “Argument 1 is less than argument 2”
<< endl;
}
if (nOperand1 == nOperand2)
{
cout << “Argument 1 is equal to argument 2”
<< endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}Program execution begins with main() as always. The program first declarestwo int variables cleverly named nOperand1 and nOperand2. It thenprompts the user to “Enter argument 1”, which it reads into nOperand1.The process is repeated for nOperand2.The program then executes a sequence of three comparisons. It first checks
whether nOperand1 is less than nOperand2. If so, the program outputs thenotification “Argument 1 is less than argument 2”. The second ifstatement displays a message if the two operands are equal in value. Thefinal comparison is true if nOperand1 is greater than nOperand2.The following shows a sample run of the BranchDemo program:Enter argument 1:5Enter argument 2:10Argument 1 is less than argument 2Press any key to continue . . .
72 Part II: Writing a Program: Decisions, DecisionsFigure 6-1 shows the flow of control graphically for this particular run.Figure 6-1:The path
taken by the
BranchDemo
program
when the
user enters
5 for the first
argument
and 10 for
the second.// enter operand1 and operand2int nOperand1;
int nOperand2;
cout << "Enter argument 1:";
cin >> nOperand1;
cout << "Enter argument 2:";
cin >> nOperand2;
// now print the results
if (nOperand1 > nOperand2)
{
cout << "Argument 1 is greater than argument 2"cout << end1;}
if (nOperand1 < nOperand2)
{
cout << "Argument 1 is less than argument 2"cout << end1;}
if (nOperand1 == nOperand2)
{
cout << "Argument 1 is equal to argument 2"cout << end1;}Entered 5
Entered 10
5 > 10 is false
5 < 10 is true
5 == 10 is falseThe way the BranchDemo program is written, all three comparisons are performed every time. This is slightly wasteful since the three conditions aremutually exclusive. For example, nOperand1 > nOperand2 can’t possiblybe true if nOperand1 < nOperand2 has already been found to be true.Later in this chapter, I show you how to avoid this waste.Say “No” to “No braces”Actually the braces are optional. Without braces, only the first expressionafter the if statement is conditional. However, it is much too easy to make amistake this way, as demonstrated in the following snippet:// Can’t have a negative age. If age is less than zero...if (nAge < 0)
cout << “Age can’t be negative; using 0” << endl;
nAge = 0;
// program continues
Chapter 6: if I Could Make My Own Decisions 73You may think that if nAge is less than 0, this program snippet outputs a message and resets nAge to zero. In fact, the program sets nAge to zero no matterwhat its original value. The preceding snippet is equivalent to the following:// Can’t have a negative age. If age is less than zero...if (nAge < 0)
{
cout << “Age can’t be negative; using 0” << endl;
}
nAge = 0;
// program continuesIt’s clear from the comments and the indent that the programmer reallymeant the following:// Can’t have a negative age. If age is less than zero...if (nAge < 0)
{
cout << “Age can’t be negative; using 0” << endl;
nAge = 0;
}
// program continuesThe C++ compiler can’t catch this type of mistake. It’s safer just to alwayssupply the braces.
C++ treats all white space the same. It ignores the alignment of expressions on
the page.
Always use braces to enclose the statements after an if statement, even ifthere is only one. You’ll generate a lot fewer errors that way.What else Is There?C++ allows the program to specify a clause after the keyword else that isexecuted if the conditional expression is false, as in the following example:if (m > n) // if m is greater than n...{
// ...then do this stuff;...
}
else // ...otherwise,...
{
// ...do this stuff
}
74 Part II: Writing a Program: Decisions, DecisionsThe else clause must appear immediately after the close brace of the ifclause. In use, the else appears as shown in the following snippet:if (nAge < 0){
cout << “Age can’t be negative; using 0.” << endl;
nAge = 0;
}
else
{
cout << “Age of “ << nAge << “ entered” << endl;
}In this case, if nAge is less than zero, the program outputs the message “Agecan’t be negative; using 0.” and then sets nAge to 0. This corresponds to the flow of control shown in the first image in Figure 6-2. If nAge isnot less than zero, the program outputs the message “Age of x entered”,where x is the value of nAge. This is shown in the second image in Figure 6-2.Figure 6-2:Flow of control through
an if andelse for
two different values
of nAge.if (nAge < 0){
cout << "Age can’t be negative; using 0."
<< end1;
nAge = 0;
}
else
{
cout << "Age of " << nAge
<< " entered" << end1;
}For nAge = –1if (nAge < 0){
cout << "Age can’t be negative; using 0."
<< end1;
nAge = 0;
}
else
{
cout << "Age of " << nAge
<< " entered" << end1;
}For nAge = 26
Chapter 6: if I Could Make My Own Decisions 75
Nesting if StatementsThe braces of an if or an else clause can contain another if statement.These are known as nested if statements. The following NestedIf programshows an example of a nested if statement in use.// NestedIf - demonstrate a nested if statement//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{Logical expressions: Do they have any value?At the beginning of this chapter, I called the comparison symbols < and > operators, and I describedstatements containing these operators as expressions. But expressions have a value and a type.What is the value and type of an expression like m > n? In C++, the type of this expression is bool(named in honor of George Boole, the inventor of Logic Calculus). Expressions of type bool canhave only one of two values: true or else false. Thus, you can write the following:bool bComparison = m > n;For historical reasons, there is a conversion between the numerical types like int and char andbool: A value of 0 is considered the same as false. Any non-zero value is considered the sameas true.Thus, the if statementif (cCharacter){
// execute this code if cCharacter is not NULL
}is the same asif (cCharacter != ‘\0’){
// execute this code if cCharacter is not NULL
}Assigning a true/false value to a character may seem a bit obtuse, but you’ll see in Chapter 16 thatit has a very useful application.
76 Part II: Writing a Program: Decisions, Decisions// enter your birth yearint nYear;
cout << “Enter your birth year: “;
cin >> nYear;
// Make determination of century
if (nYear > 2000)
{
cout << “You were born in the 21st century”
<< endl;
}
else
{
cout << “You were born in “;
if (nYear < 1950)
{
cout << “the first half”;
}
else
{
cout << “the second half”;
}
cout << “ of the 20th century”
<< endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}This program starts by asking the user for his birth year. If the birth year isgreater than 2000, then the program outputs the string “You were born inthe 21st century”.The year 2000 belongs to the 20th century, not the 21st.
If the birth year is not greater than 2000, then the program enters the elseclause of the outer if statement. This clause starts by outputting the string“You were born in” before comparing the birth year to 1950. If the birthyear is less than 1950, then the program adds the first “the first half”.If the birth year is not less than 1950, then the else clause of the inner ifstatement is executed, which tacks on the phrase “the second half”.Finally, the program adds the concluding phrase “of the 20th century”to whatever has been output so far.Chapter 6: if I Could Make My Own Decisions 77In practice, the output of the program appears as follows for three possiblevalues for birth year. First, 2002 produces the following:Enter your birth year: 2002You were born in the 21st centuryPress any key to continue . . .My own birth year of 1956 generates the following:Enter your birth year: 1956You were born in the second half of the 20th century
Press any key to continue . . .Finally, my father’s birth year of 1932 generates the third possibility:Enter your birth year: 1932You were born in the first half of the 20th century
Press any key to continue . . .I could use a nested if to avoid the unnecessary comparisons in theNestedBranchDemo program:if (nOperand1 > nOperand2){
cout << “Argument 1 is greater than argument 2”
<< endl;
}
else
{
if (nOperand1 < nOperand2)
{
cout << “Argument 1 is less than argument 2”
<< endl;
}
else
{
cout << “Argument 1 is equal to argument 2”
<< endl;
}
}This version performs the first comparison just as before. If nOperand1 isgreater than nOperand2, this snippet outputs the string “Argument 1 isgreater than argument 2”. From here, however, control jumps to thefinal closed brace, thereby skipping the remaining comparisons.
78 Part II: Writing a Program: Decisions, DecisionsIf nOperand1 is not greater than nOperand2, then the snippet performs asecond test to differentiate the case that nOperand1 is less than nOperand2from the case that they are equal in value.Figure 6-3 shows graphically the flow of control for the NestedBranchDemo
program for the same input of 5 and 10 described earlier in the chapter.Figure 6-3:The path
taken by the
NestedBranchDemo
program
when the
user enters
5 and 10
as before.// enter operand1 and operand2int nOperand1;
int nOperand2;
cout << "Enter argument 1:";
cin >> nOperand1;
cout << "Enter argument 2:";
cin >> nOperand2;
// now print the results
if (nOperand1 > nOperand2)
{
cout << "Argument 1 is greater than argument 2"
<< end1;
}
else
{
| if a(nOperand1 < nOperand2){ | 5 < 10 is true |
else
{
cout << "Argument 1 is equal to argument 2"cout << end1;}
}Entered 5
Entered 10
5 > 10 is falsePerforming the test for equality is unnecessary: If nOperand1 is neithergreater than nor less than nOperand2, then it must be equal.Compound Conditional ExpressionsThe three logical operators that can be used to create what are known ascompound conditional expressions are shown in Table 6-2.Chapter 6: if I Could Make My Own Decisions 79Table 6-2 The Logical OperatorsOperator Meaning&& AND; true if the left- and right-hand arguments are true; otherwise, false|| OR; true if either the left- or right-hand arguments is true; otherwise, false
! NOT; true if the argument on the right is false; otherwise, falseThe programmer is asking two or more questions in a conditional compoundexpression, as in the following code snippet:// make sure that nArgument is between 0 and 5if (0 < nArgument && nArgument < 5)Figure 6-4 shows how three different values of nArgument are evaluated bythis expression.Figure 6-4:The evaluation of the
compound
expression0 < n&& n <
5 for three
different
values of n.
0 < nArgument && nArgument < 5
where nArgument = –1
0 < –1 && –1 < 5
false && true
false
where nArgument = 7
0 < 7 && 7 < 5
true&&false
false
where nArgument = 2
0 <2 && 2 < 5
true && true
trueBy the way, the snippetif (m < nArgument && nArgument < n)is the normal way of coding the expression “if nArgument is betweenm and n, exclusive”. This type of test does not include the end points —that is, this test will fail if nArgument is equal to m or n. Use the <= comparison operator if you want to include the end points.80 Part II: Writing a Program: Decisions, DecisionsShort circuit evaluationLook carefully at a compound expression involving a logical AND likeif (expr1 && expr2)If expr1 is false, then the overall result of the compound expression is false, irrespective ofthe value of expr2. In fact, C++ doesn’t even evaluate expr2 if expr1 is false — false &&anything is false. This is known as short circuit evaluation because it short circuits aroundexecuting unnecessary code in order to save time.
The situation is exactly the opposite for the logical OR:if (expr1 || expr2)If expr1 is true, then the overall expression is true, irrespective of the value of expr2.Short circuit evaluation is a good thing since the resulting programs execute more quickly;
however, it can lead to unexpected results in a few cases. Consider the following admittedly contrived case:if (m <= nArgument && nArgument++ <= n)The intent is to test whether nArgument falls into the range [m, n] and to incrementnArgument as part of the test. However, short circuit evaluation means that the second testdoesn’t get executed if m <= nArgument is not true. If the second test is never evaluated,then nArgument doesn’t get incremented.Remember: If you didn’t follow that, just remember the following: Don’t put an expression that hasa side effect like incrementing a variable in a conditional.
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-3147778191066425",
enable_page_level_ads: true
});
</script>
al caractrer coding for devc++
Chapter 5Character ExpressionsIn This Chapter▶ Defining character variables and constants▶ Encoding characters▶ Declaring a string▶ Outputting characters to the consoleChapter 4 introduces the concept of the integer variable. This chapter introduces the integer’s smaller sibling, the character or char (pronounced variously as care, chair, or as in the first syllable of charcoal) to usinsiders. I have used characters in programs appearing in earlier chapters —
now it’s time to introduce them formally.Defining Character VariablesCharacter variables are declared just like integers except with the keywordchar in place of int:char inputCharacter;Character constants are defined as a single character enclosed in singlequotes, as in the following:char letterA = ‘A’;This may seem like a silly question, but what exactly is “A”? To answer that, Ineed to explain what it means to encode characters.
60 Part II: Writing a Program: Decisions, DecisionsEncoding charactersAs I mentioned in Chapter 1, everything in the computer is represented bya pattern of ones and zeros that can be interpreted as numbers. Thus, the
bit pattern 0000 0001 is the number 1 when interpreted as an integer.However, this same bit pattern means something completely different when
interpreted as an instruction by the processor. So it should come as no surprise that the computer encodes the characters of the alphabet by assigning
each a number.
Consider the character ‘A’. You could assign it any value you want as long as
we all agree. For example, you could assign a value of 1 to ‘A’, if you wanted
to. Logically, you might then assign the value 2 to ‘B’, 3 to ‘C’, and so on. In
this scheme, ‘Z’ would get the value 26. You might then start over by assigning the value 27 to ‘a’, 28 to ‘b’, right down to 52 for ‘z’. That still leaves the
digits ‘0’ through ‘9’ plus all the special symbols like space, period, comma,
slash, semicolon, and the funny characters you see when you press the
number keys while holding Shift down. Add to that the unprintable characters like tab and newline. When all is said and done, you could encode the
entire English keyboard using numbers between 1 and 127.
I say “you could” assign a value for ‘A’, ‘B’, and the remaining characters;however, that wouldn’t be a very good idea because it has already been
done. Sometime around 1963, there was a general agreement on how characters should be encoded in English. The ASCII (American Standard Coding for
Information Interchange) character encoding shown in Table 5-1 was adopted
pretty much universally except for one company. IBM published its own standard in 1963 as well. The two encoding standards duked it out for about ten
years, but by the early 1970s when C and C++ were being created, ASCII had
just about won the battle. The char type was created with ASCII characterencoding in mind.Table 5-1 The ASCII Character SetValue Char Value Char0 NULL 64 @1 Start of Heading 65 A
2 Start of Text 66 B
3 End of Text 67 C
4 End of Transmission 68 D
5 Enquiry 69 E
Chapter 5: Character Expressions 61Value Char Value Char6 Acknowledge 70 F7 Bell 71 G
8 Backspace 72 H
9 Tab 73 I
10 Newline 74 J
11 Vertical Tab 75 K
12 New Page; Form Feed 76 L
13 Carriage Return 77 M
14 Shift Out 78 N
15 Shift In 79 O
16 Data Link Escape 80 P
17 Device Control 1 81 Q
18 Device Control 2 82 R
19 Device Control 3 83 S
20 Device Control 4 84 T
21 Negative Acknowledge 85 U
22 Synchronous Idle 86 V
23 End of Transmission 87 W
24 Cancel 88 X
25 End of Medium 89 Y
26 Substitute 90 Z
27 Escape 91 [
28 File Separator 92 \
29 Group Separator 93 ]
30 Record Separator 94 ^
31 Unit Separator 95 _
32 Space 96 `
33 ! 97 a
34 “ 98 b
35 # 99 c
36 $ 100 d
37 % 101 e(continued)62 Part II: Writing a Program: Decisions, Decisions
Table 5-1 (continued)Value Char Value Char38 & 102 f39 ‘ 103 g
40 ( 104 h
41 ) 105 i
42 * 106 j
43 + 107 k
44 , 108 l
45 = 109 m
46 . 110 n
47 / 111 o
48 0 112 p
49 1 113 q
50 2 114 r
51 3 115 s
52 4 116 t
53 5 117 u
54 6 118 v
55 7 119 w
56 8 120 x
57 9 121 y
58 : 122 z
59 ; 123 {
60 < 124 |
61 = 125 }
62 > 126 ~
63 ? 127 DELThe first thing that you’ll notice is that the first 32 characters are the“unprintable” characters. That doesn’t mean that these characters are so
naughty that the censor won’t allow them to be printed — it means that they
don’t display as a symbol when printed on the printer (or on the console
for that matter). Many of these characters are no longer used or only used
Chapter 5: Character Expressions 63in obscure ways. For example, character 25 “End of Medium” was probablyprinted as the last character before the end of a reel of magnetic tape. That
was a big deal in 1963, but today it has limited use. My favorite is character
7, the Bell — this used to ring the bell on the old teletype machines. (The
Code::Blocks C++ generates a beep when you display the bell character.)
The characters starting with 32 are all printable with the exception of the last
one, 127, which is the Delete character.Example of character encodingThe following simple program allows you to play with the ASCII character set:// CharacterEncoding - allow the user to enter a// numeric value then print that value
// out as a character
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// Prompt the user for a value
int nValue;
cout << “Enter decimal value of char to print:”;
cin >> nValue;
// Now print that value back out as a character
char cValue = (char)nValue;
cout << “The char you entered was [“ << cValue
<< “]” << endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}This program begins by prompting the user to “Enter decimal value ofa char to print”. The program then reads the value entered by the userinto the int variable nValue.The program then assigns this value to a char variable cValue.64 Part II: Writing a Program: Decisions, DecisionsThe (char) appearing in front of nValue is called a cast. In this case, itcasts the value of nValue from an int to a char. I could have performed theassignment without the cast as incValue = nValue;However, the type of the variables wouldn’t match: The value on the right ofthe assignment is an int, while the value on the left is a char. C++ will perform the assignment anyway, but it will generally complain about such conversions by generating a warning during the build step. The cast converts thevalue in nValue to a char before performing the assignment:cValue = (char)nValue; // cast nValue to a char before// assigning the value to cValueThe final line outputs the character cValue within a set of square brackets.The following shows a few sample runs of the program. In the first run, I
entered the value 65, which Table 5-1 shows as the character ‘A’:Enter decimal value of char to print:65The char you entered was [A]Press any key to continue . . .The second time I entered the value 97, which corresponds to the character ‘a’:Enter decimal value of char to print:97The char you entered was [a]Press any key to continue . . .On subsequent runs, I tried special characters:Enter decimal value of char to print:36The char you entered was [$]Press any key to continue . . .The value 7 didn’t print anything, but did cause my PC to issue a loud beepthat scared the heck out of me.
The value 10 generated the following odd output:Enter decimal value of char to print:10The char you entered was []
Press any key to continue . . .Referring to Table 5-1, you can see that 10 is the newline character. This character doesn’t actually print anything but causes subsequent output to startChapter 5: Character Expressions 65at the beginning of the next line, which is exactly what happened in this case:The closed brace appears by itself at the beginning of the next line when following a newline character.
The endl that appears at the end of many of the output commands thatyou’ve seen so far generates a newline. It also does a few other things, which
you’ll see in Chapter 31.Encoding Strings of CharactersTheoretically, you could print anything you want using individual characters. However, that could get really tedious as the following code snippetdemonstrates:cout << ‘E’ << ‘n’ << ‘t’ << ‘e’ << ‘r’ << ‘ ‘<< ‘d’ << ‘e’ << ‘c’ << ‘i’ << ‘m’ << ‘a’
<< ‘l’ << ‘ ‘ << ‘v’ << ‘a’ << ‘l’ << ‘u’
<< ‘e’ << ‘ ‘ << ‘o’ << ‘f’ << ‘ ‘ << ‘c’
<< ‘h’ << ‘a’ << ‘r’ << ‘ ‘ << ‘t’ << ‘o’
<< ‘ ‘ << ‘p’ << ‘r’ << ‘i’ << ‘n’ << ‘t’
<< ‘:’;C++ allows you to encode a sequence of characters by enclosing the string indouble quotes:cout << “Enter decimal value of char to print:”;I’ll have a lot more to say about character strings in Chapter 16.Special Character ConstantsYou can code a normal, printable character by placing it in single quotes:char cSpace = ‘ ‘;You can code any character you want, whether printable or not, by placingits octal value after a backslash:char cSpace = ‘\040’;A constant appearing with a leading zero is assumed to be octal, also knownas base 8.
66 Part II: Writing a Program: Decisions, DecisionsYou can code characters in base 16, hexadecimal, by preceding the numberwith a backslash followed by a small x as in the following example:char cSpace = ‘\x20’;The decimal value 32 is equal to 40 in base 8 and 20 in base 16. Don’t worry ifyou don’t feel comfortable with octal or hexadecimal. C++ provides shortcuts
for the most common characters.
C++ provides a name for some of the unprintable characters that are particularly useful. Some of the more common ones are shown in Table 5-2.Table 5-2 Some of the Special C++ CharactersChar Special Symbol Char Special Symbol‘ \’ Newline \n“ \” Carriage Return \r
\ \\ Tab \t
NULL \0 Bell \aThe most common is the newline character, which is nicknamed ‘\n’. In addition, you must use the backslash if you want to print the single quote character:char cQuote = ‘\’’;Since C++ normally interprets a single quote mark as enclosing a character,you have to precede a single quote mark with a backslash character to tell it,
“Hey, this single quote is not enclosing a character, this is the character.”
In addition, the character ‘\\’ is a single backslash.
This leads to one of the more unfortunate coincidences in C++. In Windows,
the backslash is used in filenames as in the following:C:\\Base Directory\Subdirectory\File NameThis is encoded in C++ with each backslash replaced by a pair of backslashesas follows:“C:\\\\Base Directory\\Subdirectory\\File Name”Chapter 5: Character Expressions 67Wide load aheadBy the early 1970s when C and C++ wereinvented, the 128-character ASCII character
set had pretty much beat out all rivals. So it
was logical that the char type was definedto accommodate the ASCII character set.
This character set was fine for English but
became overly restrictive when programmers
tried to write applications for other European
languages.
Fortunately, C and C++ had provided enough
room in the char for 256 different characters.Standards committees got busy and used the
characters between 128 and 255 for characters that occur in European languages but not
English, such as umlauts and accented characters. You can see the results of their handy work
using the example CharacterEncodingprogram from this chapter: Enter 142 and theprogram prints out an Ä.
No matter what you do, the char variable isjust not large enough to handle all of the many
different alphabets, such as Cyrillic, Hebrew,
Arabic, and Korean — not to mention the many
thousands of Chinese kanji symbols. Something
had to give.
C++ responded first by introducing the “wide
character” of type wchar_t. This wasintended to implement whatever wide character set that is native to the host operating
system. On Windows, that would be the variant of Unicode known as UTF-2 or UTF-16.
(Here the 2 stands for two bytes, the size of
each wide character, whereas the 16 stands
for 16 bits.) However, Macintosh’s OS X uses
a different variant of Unicode known as UTF-8.
Unicode can display not only every alphabet on
the planet but also the kanjis used in Chinese
and Japanese. The 2009 update to the C++
standard added two further types, char16_tand char32_t, which implement specificallyUTF-16 and UTF-32.
For almost every feature that I describe in this
book for handling character variables, there
is an equivalent feature for the wide character types; programming Unicode, however, is
beyond the scope of a beginning text.
now it’s time to introduce them formally.Defining Character VariablesCharacter variables are declared just like integers except with the keywordchar in place of int:char inputCharacter;Character constants are defined as a single character enclosed in singlequotes, as in the following:char letterA = ‘A’;This may seem like a silly question, but what exactly is “A”? To answer that, Ineed to explain what it means to encode characters.
60 Part II: Writing a Program: Decisions, DecisionsEncoding charactersAs I mentioned in Chapter 1, everything in the computer is represented bya pattern of ones and zeros that can be interpreted as numbers. Thus, the
bit pattern 0000 0001 is the number 1 when interpreted as an integer.However, this same bit pattern means something completely different when
interpreted as an instruction by the processor. So it should come as no surprise that the computer encodes the characters of the alphabet by assigning
each a number.
Consider the character ‘A’. You could assign it any value you want as long as
we all agree. For example, you could assign a value of 1 to ‘A’, if you wanted
to. Logically, you might then assign the value 2 to ‘B’, 3 to ‘C’, and so on. In
this scheme, ‘Z’ would get the value 26. You might then start over by assigning the value 27 to ‘a’, 28 to ‘b’, right down to 52 for ‘z’. That still leaves the
digits ‘0’ through ‘9’ plus all the special symbols like space, period, comma,
slash, semicolon, and the funny characters you see when you press the
number keys while holding Shift down. Add to that the unprintable characters like tab and newline. When all is said and done, you could encode the
entire English keyboard using numbers between 1 and 127.
I say “you could” assign a value for ‘A’, ‘B’, and the remaining characters;however, that wouldn’t be a very good idea because it has already been
done. Sometime around 1963, there was a general agreement on how characters should be encoded in English. The ASCII (American Standard Coding for
Information Interchange) character encoding shown in Table 5-1 was adopted
pretty much universally except for one company. IBM published its own standard in 1963 as well. The two encoding standards duked it out for about ten
years, but by the early 1970s when C and C++ were being created, ASCII had
just about won the battle. The char type was created with ASCII characterencoding in mind.Table 5-1 The ASCII Character SetValue Char Value Char0 NULL 64 @1 Start of Heading 65 A
2 Start of Text 66 B
3 End of Text 67 C
4 End of Transmission 68 D
5 Enquiry 69 E
Chapter 5: Character Expressions 61Value Char Value Char6 Acknowledge 70 F7 Bell 71 G
8 Backspace 72 H
9 Tab 73 I
10 Newline 74 J
11 Vertical Tab 75 K
12 New Page; Form Feed 76 L
13 Carriage Return 77 M
14 Shift Out 78 N
15 Shift In 79 O
16 Data Link Escape 80 P
17 Device Control 1 81 Q
18 Device Control 2 82 R
19 Device Control 3 83 S
20 Device Control 4 84 T
21 Negative Acknowledge 85 U
22 Synchronous Idle 86 V
23 End of Transmission 87 W
24 Cancel 88 X
25 End of Medium 89 Y
26 Substitute 90 Z
27 Escape 91 [
28 File Separator 92 \
29 Group Separator 93 ]
30 Record Separator 94 ^
31 Unit Separator 95 _
32 Space 96 `
33 ! 97 a
34 “ 98 b
35 # 99 c
36 $ 100 d
37 % 101 e(continued)62 Part II: Writing a Program: Decisions, Decisions
Table 5-1 (continued)Value Char Value Char38 & 102 f39 ‘ 103 g
40 ( 104 h
41 ) 105 i
42 * 106 j
43 + 107 k
44 , 108 l
45 = 109 m
46 . 110 n
47 / 111 o
48 0 112 p
49 1 113 q
50 2 114 r
51 3 115 s
52 4 116 t
53 5 117 u
54 6 118 v
55 7 119 w
56 8 120 x
57 9 121 y
58 : 122 z
59 ; 123 {
60 < 124 |
61 = 125 }
62 > 126 ~
63 ? 127 DELThe first thing that you’ll notice is that the first 32 characters are the“unprintable” characters. That doesn’t mean that these characters are so
naughty that the censor won’t allow them to be printed — it means that they
don’t display as a symbol when printed on the printer (or on the console
for that matter). Many of these characters are no longer used or only used
Chapter 5: Character Expressions 63in obscure ways. For example, character 25 “End of Medium” was probablyprinted as the last character before the end of a reel of magnetic tape. That
was a big deal in 1963, but today it has limited use. My favorite is character
7, the Bell — this used to ring the bell on the old teletype machines. (The
Code::Blocks C++ generates a beep when you display the bell character.)
The characters starting with 32 are all printable with the exception of the last
one, 127, which is the Delete character.Example of character encodingThe following simple program allows you to play with the ASCII character set:// CharacterEncoding - allow the user to enter a// numeric value then print that value
// out as a character
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// Prompt the user for a value
int nValue;
cout << “Enter decimal value of char to print:”;
cin >> nValue;
// Now print that value back out as a character
char cValue = (char)nValue;
cout << “The char you entered was [“ << cValue
<< “]” << endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}This program begins by prompting the user to “Enter decimal value ofa char to print”. The program then reads the value entered by the userinto the int variable nValue.The program then assigns this value to a char variable cValue.64 Part II: Writing a Program: Decisions, DecisionsThe (char) appearing in front of nValue is called a cast. In this case, itcasts the value of nValue from an int to a char. I could have performed theassignment without the cast as incValue = nValue;However, the type of the variables wouldn’t match: The value on the right ofthe assignment is an int, while the value on the left is a char. C++ will perform the assignment anyway, but it will generally complain about such conversions by generating a warning during the build step. The cast converts thevalue in nValue to a char before performing the assignment:cValue = (char)nValue; // cast nValue to a char before// assigning the value to cValueThe final line outputs the character cValue within a set of square brackets.The following shows a few sample runs of the program. In the first run, I
entered the value 65, which Table 5-1 shows as the character ‘A’:Enter decimal value of char to print:65The char you entered was [A]Press any key to continue . . .The second time I entered the value 97, which corresponds to the character ‘a’:Enter decimal value of char to print:97The char you entered was [a]Press any key to continue . . .On subsequent runs, I tried special characters:Enter decimal value of char to print:36The char you entered was [$]Press any key to continue . . .The value 7 didn’t print anything, but did cause my PC to issue a loud beepthat scared the heck out of me.
The value 10 generated the following odd output:Enter decimal value of char to print:10The char you entered was []
Press any key to continue . . .Referring to Table 5-1, you can see that 10 is the newline character. This character doesn’t actually print anything but causes subsequent output to startChapter 5: Character Expressions 65at the beginning of the next line, which is exactly what happened in this case:The closed brace appears by itself at the beginning of the next line when following a newline character.
The endl that appears at the end of many of the output commands thatyou’ve seen so far generates a newline. It also does a few other things, which
you’ll see in Chapter 31.Encoding Strings of CharactersTheoretically, you could print anything you want using individual characters. However, that could get really tedious as the following code snippetdemonstrates:cout << ‘E’ << ‘n’ << ‘t’ << ‘e’ << ‘r’ << ‘ ‘<< ‘d’ << ‘e’ << ‘c’ << ‘i’ << ‘m’ << ‘a’
<< ‘l’ << ‘ ‘ << ‘v’ << ‘a’ << ‘l’ << ‘u’
<< ‘e’ << ‘ ‘ << ‘o’ << ‘f’ << ‘ ‘ << ‘c’
<< ‘h’ << ‘a’ << ‘r’ << ‘ ‘ << ‘t’ << ‘o’
<< ‘ ‘ << ‘p’ << ‘r’ << ‘i’ << ‘n’ << ‘t’
<< ‘:’;C++ allows you to encode a sequence of characters by enclosing the string indouble quotes:cout << “Enter decimal value of char to print:”;I’ll have a lot more to say about character strings in Chapter 16.Special Character ConstantsYou can code a normal, printable character by placing it in single quotes:char cSpace = ‘ ‘;You can code any character you want, whether printable or not, by placingits octal value after a backslash:char cSpace = ‘\040’;A constant appearing with a leading zero is assumed to be octal, also knownas base 8.
66 Part II: Writing a Program: Decisions, DecisionsYou can code characters in base 16, hexadecimal, by preceding the numberwith a backslash followed by a small x as in the following example:char cSpace = ‘\x20’;The decimal value 32 is equal to 40 in base 8 and 20 in base 16. Don’t worry ifyou don’t feel comfortable with octal or hexadecimal. C++ provides shortcuts
for the most common characters.
C++ provides a name for some of the unprintable characters that are particularly useful. Some of the more common ones are shown in Table 5-2.Table 5-2 Some of the Special C++ CharactersChar Special Symbol Char Special Symbol‘ \’ Newline \n“ \” Carriage Return \r
\ \\ Tab \t
NULL \0 Bell \aThe most common is the newline character, which is nicknamed ‘\n’. In addition, you must use the backslash if you want to print the single quote character:char cQuote = ‘\’’;Since C++ normally interprets a single quote mark as enclosing a character,you have to precede a single quote mark with a backslash character to tell it,
“Hey, this single quote is not enclosing a character, this is the character.”
In addition, the character ‘\\’ is a single backslash.
This leads to one of the more unfortunate coincidences in C++. In Windows,
the backslash is used in filenames as in the following:C:\\Base Directory\Subdirectory\File NameThis is encoded in C++ with each backslash replaced by a pair of backslashesas follows:“C:\\\\Base Directory\\Subdirectory\\File Name”Chapter 5: Character Expressions 67Wide load aheadBy the early 1970s when C and C++ wereinvented, the 128-character ASCII character
set had pretty much beat out all rivals. So it
was logical that the char type was definedto accommodate the ASCII character set.
This character set was fine for English but
became overly restrictive when programmers
tried to write applications for other European
languages.
Fortunately, C and C++ had provided enough
room in the char for 256 different characters.Standards committees got busy and used the
characters between 128 and 255 for characters that occur in European languages but not
English, such as umlauts and accented characters. You can see the results of their handy work
using the example CharacterEncodingprogram from this chapter: Enter 142 and theprogram prints out an Ä.
No matter what you do, the char variable isjust not large enough to handle all of the many
different alphabets, such as Cyrillic, Hebrew,
Arabic, and Korean — not to mention the many
thousands of Chinese kanji symbols. Something
had to give.
C++ responded first by introducing the “wide
character” of type wchar_t. This wasintended to implement whatever wide character set that is native to the host operating
system. On Windows, that would be the variant of Unicode known as UTF-2 or UTF-16.
(Here the 2 stands for two bytes, the size of
each wide character, whereas the 16 stands
for 16 bits.) However, Macintosh’s OS X uses
a different variant of Unicode known as UTF-8.
Unicode can display not only every alphabet on
the planet but also the kanjis used in Chinese
and Japanese. The 2009 update to the C++
standard added two further types, char16_tand char32_t, which implement specificallyUTF-16 and UTF-32.
For almost every feature that I describe in this
book for handling character variables, there
is an equivalent feature for the wide character types; programming Unicode, however, is
beyond the scope of a beginning text.
while and loop in dev c++
Chapter 9while Running in CirclesIn This Chapter▶ Looping using the while statement▶ Breaking out of the middle of a loop▶ Avoiding the deadly infinite loop▶ Nesting loops within loopsDecision making is a fundamental part of almost every program you write, which I initially emphasize in Chapter 1. However, another fundamental feature that is clear — even in the simple Lug Nut Removal algorithm —is the ability to loop. That program turned the wrench in a loop until the lug
nut fell off, and it looped from one lug nut to the other until the entire wheel
came off. This chapter introduces you to two of the three looping constructs
in C++.Creating a while LoopThe while loop has the following format:while (expression){
// stuff to do in a loop
}
// continue here once expression is falseWhen a program comes upon a while loop, it first evaluates the expressionin the parentheses. If this expression is true, then control passes to the firstline inside the {. When control reaches the }, the program returns back tothe expression and starts over. Control continues to cycle through the code
in the braces until expression evaluates to false (or until something elsebreaks the loop — more on that a little later in this chapter).
100 Part III: Becoming a Functional ProgrammerThe following Factorial program demonstrates the while loop:Factorial(N) = N * (N-1) * (N-2) * ... * 1//// Factorial - calculate factorial using the while// construct.//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter the number to calculate the factorial of
int nTarget;
cout << “This program calculates factorial.\n”
<< “Enter a number to take factorial of: “;
cin >> nTarget;
// start with an accumulator that’s initialized to 1
int nAccumulator = 1;
int nValue = 1;
while (nValue <= nTarget)
{
cout << nAccumulator << “ * “
<< nValue << “ equals “;
nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
nValue++;
}
// display the result
cout << nTarget << “ factorial is “
<< nAccumulator << endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The program starts by prompting the user for a target value. The program readsthis value into nTarget. The program then initializes both nAccumulatorand nValue to 1 before entering the loop.(Pay attention — this is the interesting part.) The program compares nValueto nTarget. Assume that the user had entered a target value of 5. On thefirst loop, the question becomes, “Is 1 less than or equal to 5?” The answer is
Chapter 9: while Running in Circles 101obviously true, so control flows into the loop. The program outputsthe value of nAccumulator (1) and nValue (also 1) before multiplyingnAccumulator by nValue and storing the result back into nAccumulator.The last statement in the loop increments nValue from 1 to 2.That done, control passes back up to the while statement where nValue(now 2) is compared to nTarget (still 5). “Is 2 less than or equal to 5?”Clearly, yes; so control flows back into the loop. nAccumulator is now set tothe result of nAccumulator (1) times nValue (2). The last statement increments nValue to 3.This cycle of fun continues until nValue reaches the value 6, which is nolonger less than or equal to 5. At that point, control passes to the first statement beyond the closed brace }. This is shown graphically in Figure 9-1.Figure 9-1:Controlcontinues
to cycle
through
the body of
a whileloop untilthe conditional
expression
evaluates tofalse.while (nValue <= nTarget){
cout << nAccumulator << " * "
<< nValue << " equals ";
nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
nValue++;
}For nValue <= nTarget is truewhile (nValue <= nTarget)
<< nValue << " equals ";nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
nValue++;
}The actual output from the program appears as follows for an input value of 5:This program calculates factorial.Enter a number to take factorial of: 51 * 1 equals 11 * 2 equals 2
2 * 3 equals 6
6 * 4 equals 24
24 * 5 equals 120
5 factorial is 120
Press any key to continue . . .
102 Part III: Becoming a Functional ProgrammerYou are not guaranteed that the code within the braces of a while loop isexecuted at all: If the conditional expression is false the first time it’s evaluated, control passes around the braces without ever diving in. Consider, for
example, the output from the Factorial program when the user enters a target
value of 0:This program calculates factorial.Enter a number to take factorial of: 0
0 factorial is 1
Press any key to continue . . .No lines of output are generated from within the loop because the condition“Is nValue less than or equal to 0” was false even for the initial value of 1.The body of the while loop was never executed.Breaking out of the Middle of a LoopSometimes the condition that causes you to terminate a loop doesn’t occuruntil somewhere in the middle of the loop. This is especially true when testing user input for some termination character. C++ provides these two control commands to handle this case:✓ break exits the inner most loop immediately.✓ continue passes control back to the top of the loop.The following Product program demonstrates both break and continue.This program multiplies positive values entered by the user until the user
enters a negative number. The program ignores zero.//// Product - demonstrate the use of break and continue.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter the number to calculate the factorial of
cout << “This program multiplies the numbers\n”
<< “entered by the user. Enter a negative\n”
<< “number to exit. Zeroes are ignored.\n”
<< endl;
int nProduct = 1;
while (true)
{
Chapter 9: while Running in Circles 103int nValue;cout << “Enter a number to multiply: “;
cin >> nValue;
if (nValue < 0)
{
cout << “Exiting.” << endl;
break;
}
if (nValue == 0)
{
cout << “Ignoring zero.” << endl;
continue;
}
// multiply accumulator by this value and
// output the result
cout << nProduct << “ * “ << nValue;
nProduct *= nValue;
cout << “ is “ << nProduct << endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The program starts out with an initial value of nProduct of 1. The programthen evaluates the logical expression true to see if it’s true. It is.There aren’t too many rules that hold in C++ without exception, but here’s
one: true is always true.The program then enters the loop to prompt the user for another value to
multiply times nProduct, the accumulated product of all numbers enteredso far. If the value entered is negative, then the program outputs the phrase“Exiting.” before executing the break, which passes control out of the loop.If the value entered is not negative, control passes to the second if statement.If nValue is equal to zero, then the program outputs the messages “Ignoringzero.” before executing the continue statement which passes control backto the top of the loop to allow the user to enter another value.
If nValue is neither less than zero nor zero, then control flows down towhere nValue is multiplied by nProduct using the special assignment operator (see Chapter 4 if you don’t remember this one):nProduct *= nValue;104 Part III: Becoming a Functional ProgrammerThis expression is the same as:nProduct = nProduct * nValue;The output from a sample run from this program appears as follows:This program multiplies the numbersentered by the user. Enter a negative
number to exit. Zeroes are ignored.
Enter a number to multiply: 21 * 2 is 2Enter a number to multiply: 52 * 5 is 10Enter a number to multiply: 0Ignoring zero.Enter a number to multiply: 310 * 3 is 30Enter a number to multiply: -1Exiting.Press any key to continue . . .Why is “break” necessary?You might be tempted to wonder why break is really necessary. What if I had coded the loop in
the Product example program asint nProduct = 1;int nValue = 1;
while (nValue > 0)
{
cout << “Enter a number to multiply: “;
cin >> nValue;
cout << nProduct << “ * “ << nValue;
nProduct *= nValue;
cout << “ is “ << nProduct << endl;
}You might think that as soon as the user enters a negative value for nValue, the expressionnValue > 0 is no longer true and control immediately exits the loop — unfortunately, this is
not the case.
The problem is that the logical expression is only evaluated at the beginning of each pass through
the loop. Control doesn’t immediately fly out of the body of the loop as soon as the condition ceases
to be true. An if statement followed by a break allows me to move the conditional expression
into the body of the loop where the value of nValue is assigned.
Chapter 9: while Running in Circles 105
Nested LoopsThe body of a loop can itself contain a loop in what is known as nested loops. Theinner loop must execute to completion during each time through the outer loop.
I have created a program that uses nested loops to create a multiplication
table of the form:0 1 2 3 4 5 6 7 8 90 0*0 0*1 0*2 0*3 0*4 0*5 0*6 0*7 0*8 0*9
1 1*0 1*1 1*2 1*3 1*4 1*5 1*6 1*7 1*8 1*9
2 2*0 2*1 2*2 2*3 2*4 2*5 2*6 2*7 2*8 2*9
//... and so on...You can see that for row 0, the program will need to iterate from column 0through column 9. The program will repeat the process for row 1 and again for
row 2 and so on right down to row 9. This implies the need for two loops: an inner
loop to iterate over the columns and a second outer loop to iterate over the rows.
Each position in the table is simply the row number times the column number.
This is exactly how the following NestedLoops program works://// NestedLoops - this program uses a nested loop to
// calculate the multiplication table.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// display the column headings
int nColumn = 0;
cout << “ “;
while (nColumn < 10)
{
// set the display width to two characters
// (even for one digit numbers)
cout.width(2);
// now display the column number
cout << nColumn << “ “;
// increment to the next column
nColumn++;
}
cout << endl;
// now go loop through the rows
int nRow = 0;
106 Part III: Becoming a Functional Programmerwhile (nRow < 10){
// start with the row value
cout << nRow << “ - “;
// now for each row, start with column 0 and
// go through column 9
nColumn = 0;
while(nColumn < 10)
{
// display the product of the column*row
// (use 2 characters even when product is
// a single digit)
cout.width(2);
cout << nRow * nColumn << “ “;
// go to next column
nColumn++;
}
// go to next row
nRow++;
cout << endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The first section creates the column headings. This section initializes nColumnto 0. It then iterates through nColumn printing out its value separated bya space until nColumn reaches 10. At this point, the program exits the firstloop and then tacks a new line on the end to finish the row. This is shown
graphically in Figure 9-2.
Executing just this section alone generates the following output:0 1 2 3 4 5 6 7 8 9This program demonstrates an unfair advantage that I have. The expressioncout.width(2) sets the display width to two columns — C++ will pad aspace on the left for single-digit numbers. I know it’s cheating to make use of
a feature that I don’t present to the reader until Chapter 31, but it’s very difficult to get the columns to line up without resorting to fixed-width output.
The second set of loops, the nested loops, starts at nRow equal to 0. The program prints out the row number followed by a dash before launching into aChapter 9: while Running in Circles 107second loop that starts nColumn at 0 again and iterates it back up to 9. Foreach pass through this inner loop, the program sets the output width to two
spaces and then displays nRow * nColumn followed by a space.Figure 9-2:The firstloop outputs
the column
headings.// display the column headingsint nColumn = 0;
while (nColumn < 10)
{
// now display the column number
cout << nColumn << " ";
// increment to the next column
nColumn++;
}
//go to the next row
cout << end1;Output: 0 1 2 3 4 5 6 7 8 9The display width resets itself each time you output something, so it’s necessary to set it back to two each time before outputting a number.The program outputs a newline to move output to the next row each time it
increments nRow. This is shown graphically in Figure 9-3.The output from this program appears as follows:0 1 2 3 4 5 6 7 8 90 - 0 0 0 0 0 0 0 0 0 0
1 - 0 1 2 3 4 5 6 7 8 9
2 - 0 2 4 6 8 10 12 14 16 18
3 - 0 3 6 9 12 15 18 21 24 27
4 - 0 4 8 12 16 20 24 28 32 36
5 - 0 5 10 15 20 25 30 35 40 45
6 - 0 6 12 18 24 30 36 42 48 54
7 - 0 7 14 21 28 35 42 49 56 63
8 - 0 8 16 24 32 40 48 56 64 72
9 - 0 9 18 27 36 45 54 63 72 81
Press any key to continue . . .There is nothing magic about 0 through 9 in this table. I could just have easilycreated a 12 x 12 multiplication table (or any other combination) by changing
the comparison expression in the three while loops. However, for anythinglarger than 10 x 10, you will need to increase the minimum width to accommodate the three-digit products. Use cout.width(3).108 Part III: Becoming a Functional ProgrammerFigure 9-3:The innerloop iterates
from left to
right across
the columns, while
the outer
loop iterates
from top
to bottom
down the
rows.// now go loop through the rows
int nRow = 0;
while (nRow < 10)
{
// start with the row value
cout << nRow << " – ";
// now for each row, start with column 0 and
// go through column 9
nColumn = 0;
while(nColumn < 10)
{
cout << nRow * nColumn << " ";
// go to next column
nColumn++;
}
// go to next row
nRow++;
cout << end1;
}0 * 0 0 * 1 0 * 2 0 * 3 0 * 4 0 * 5 0 * 6 0 * 7 0 * 8 0 * 9
1 * 0 1* 1 1 * 2 1 * 3 1 * 4 1 * 5 1 * 6 1 * 7 1 * 8 1 * 9
2 * 0 2 * 1 2 * 2 2 * 3 2 * 4 2 * 5 2 * 6 2 * 7 2 * 8 2 * 9Output:Inner loop
Outer
loop
Chapter 10Looping for the Fun of ItIn This Chapter▶ Introducing the for loop▶ Reviewing an example ForFactorial program▶ Using the comma operator to get more done in a single for loopThe most basic of all control structures is the topic of Chapter 9. This chapter introduces you its sibling, the while loop, which is the for loop.Though not quite as flexible, the for loop is actually the more popular of thetwo — it has a certain elegance that is hard to ignore.The for Parts of Every LoopIf you look again at the examples in Chapter 9, you’ll notice that most loopshave four essential parts. (This feels like breaking down a golf swing into its
constituent parts.)✓ The setup: Usually the setup involves declaring and initializing anincrement variable. This generally occurs immediately before thewhile.✓ The test expression: The expression within the while loop that willcause the program to either execute the loop or exit and continue
on. This always occurs within the parentheses following the keywordwhile.✓ The body: This is the code within the braces.✓ The increment: This is where the increment variable is incremented.This usually occurs at the end of the body.
In the case of the Factorial program, the four parts looked like this:int nValue = 1; // the setupwhile (nValue <= nTarget) // the test expression
{ // the body
cout << nAccumulator << “ * “
110 Part III: Becoming a Functional Programmer<< nValue << “ equals “;nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
nValue++; // the increment
}The for loop incorporates these four parts into a single structure using thekeyword for:for(setup; test expression; increment){
body;
}The flow is shown graphically in Figure 10-1.1. As the CPU comes innocently upon the for keyword, control is divertedto the setup clause.2. Once the setup has been performed, control moves over to the testexpression.3. (a) If the test expression is true, control passes to the body of thefor loop.(b) If the test expression is false, control passes to the next statement after the closed brace.4. Once control has passed through the body of the loop, the CPU is forced
to perform a U-turn back up to the increment section of the loop.That done, control returns to the test expression and back to Step 3.Figure 10-1:The flow inand around
the forloop.for(setup; test expression; increment)
}1 24
5
Chapter 10: Looping for the Fun of It 111This for loop is completely equivalent to the following while loop:setup;while(test expression)
{
body;
increment;
}Looking at an ExampleThe following example program is the Factorial program written as a for loop(this program appears on the enclosed CD-ROM as ForFactorial)://// ForFactorial - calculate factorial using the for
// construct.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter the number to calculate the factorial of
int nTarget;
cout << “This program calculates factorial.\n”
<< “Enter a number to take factorial of: “;
cin >> nTarget;
// start with an accumulator that’s initialized to 1
int nAccumulator = 1;
for(int nValue = 1; nValue <= nTarget; nValue++)
{
cout << nAccumulator << “ * “
<< nValue << “ equals “;
nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
}
// display the result
cout << nTarget << “ factorial is “
112 Part III: Becoming a Functional Programmer<< nAccumulator << endl;// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The logic of this ForFactorial program is virtually identical to its olderFactorial twin: The program prompts the user to enter a number to take the
factorial of. It then initializes nAccumulator to 1 before entering the loopthat calculates the factorial.
ForFactorial creates an increment variable, nValue, that it initializes to 1in the setup clause of the for statement. That done, the program comparesnValue to nTarget, the value entered by the user in the test expressionsection of the for. If nValue is less than or equal to nTarget, control entersthe body of the loop where nAccumulator is multiplied by nValue.That done, control flows back up to the increment section of the for loop.This expression, nValue++, increments nValue by 1. Flow then moves tothe test expression, where nValue is compared with nTarget and theprocess repeated until eventually nValue exceeds the value of nTarget. Atthat point, control passes to the next statement after the closed brace.
The output from this program appears as follows:This program calculates factorials of user input.Enter a negative number to exit
Enter number: 5
5 factorial is 120
Enter number: 6
6 factorial is 720
Enter number: -1
Press any key to continue . . .All four sections of the for loop are optional. An empty setup, body, orincrement section has no effect; that is, it does nothing. (That makes sense.)An empty test expression is the same as true. (This is the only thing thatwould make sense — if it evaluated to false, then the body of the for loopwould never get executed, and the result would be useless.)
A variable defined within the setup section of a for loop is only defined withinthe for loop. It is no longer defined once control exits the loop.Chapter 10: Looping for the Fun of It 113
Getting More Done with
the Comma OperatorThere is a seemingly useless operator that I haven’t mentioned (up until now,that is) known as the comma operator. It appears as follows:expression1, expression2;This says execute expression1 and then execute expression2. The resultingvalue and type of the overall expression is the same as that of expression2.Thus, I could say something like the following:int i;int j;
i = 1, j = 2;Why would I ever want to do such a thing, you ask? Answer: You wouldn’texcept when writing for loops.The following CommaOperator program demonstrates the comma operator in
combat. This program calculates the products of pairs of numbers. If the operator enters N, the program outputs 1 * N, 2 * N-1, 3 * N-2, and so on, all the
way up to N * 1. (This program doesn’t do anything particularly useful. You’ll
see the comma operator used to effect when discussing arrays in Chapter 15.)//// CommaOperator - demonstrate how the comma operator
// is used within a for loop.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter a target number
int nTarget;
cout << “Enter maximum value: “;
cin >> nTarget;
114 Part III: Becoming a Functional Programmerfor(int nLower = 1, nUpper = nTarget;nLower <= nTarget; nLower++, nUpper--)
{
cout << nLower << “ * “
<< nUpper << “ equals “
<< nLower * nUpper << endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The program first prompts the operator for a target value, which is read intonTarget. It then moves to the for loop. However, this time not only do youwant to increment a variable from 1 to nTarget, you also want to decrementa second variable from nTarget down to 1.Here the setup clause of the for loop declares a variable nLower that it initializes to 1 and a second variable nTarget that gets initialized to nTarget.The body of the loop displays nLower, nUpper, and the product nLower* nTarget. The increment section increments nLower and decrementsnUpper.The output from the program appears as follows:Enter maximum value: 151 * 15 equals 152 * 14 equals 28
3 * 13 equals 39
4 * 12 equals 48
5 * 11 equals 55
6 * 10 equals 60
7 * 9 equals 63
8 * 8 equals 64
9 * 7 equals 63
10 * 6 equals 60
11 * 5 equals 55
12 * 4 equals 48
13 * 3 equals 39
14 * 2 equals 28
15 * 1 equals 15
Press any key to continue . . .
Chapter 10: Looping for the Fun of It 115In this example run, I entered 15 as the target value. You can see how nLowerincrements in a straight line from 1 to 15, while nUpper makes its way from15 down to 1.
Actually, the output from this program is mildly interesting: No matter what
you enter, the value of the product increases rapidly at first as nLower increments from 1. Fairly quickly, however, the curve flattens out and asymptotically approaches the maximum value in the middle of the range beforeheading back down. The maximum value for the product always occurs whennLower and nUpper are equal.Could I have made the earlier for loop work without using the comma operator? Absolutely. I could have taken either variable, nLower or nUpper, out ofthe for loop and handled them as separate variables. Consider the followingcode snippet:nUpper = nTarget;for(int nLower = 1; nLower <= nTarget; nLower++)
{
cout << nLower << “ * “
<< nUpper << “ equals “
<< nLower * nUpper << endl;
nUpper--;
}This version would have worked just as well.The for loop can’t do anything that a while loop cannot do. In fact, any forloop can be converted into an equivalent while loop. However, because of itscompactness, you will see the for loop a lot more often.Up to and including this chapter, all of the programs have been one monolithic whole stretching from the opening brace after main() to the corresponding closing brace. This is okay for small programs, but it would bereally cool if you could divide your program into smaller bites that could be
digested separately. That is the goal of the next chapter on functions.
116 Part III: Becoming a Functional Programmer
nut fell off, and it looped from one lug nut to the other until the entire wheel
came off. This chapter introduces you to two of the three looping constructs
in C++.Creating a while LoopThe while loop has the following format:while (expression){
// stuff to do in a loop
}
// continue here once expression is falseWhen a program comes upon a while loop, it first evaluates the expressionin the parentheses. If this expression is true, then control passes to the firstline inside the {. When control reaches the }, the program returns back tothe expression and starts over. Control continues to cycle through the code
in the braces until expression evaluates to false (or until something elsebreaks the loop — more on that a little later in this chapter).
100 Part III: Becoming a Functional ProgrammerThe following Factorial program demonstrates the while loop:Factorial(N) = N * (N-1) * (N-2) * ... * 1//// Factorial - calculate factorial using the while// construct.//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter the number to calculate the factorial of
int nTarget;
cout << “This program calculates factorial.\n”
<< “Enter a number to take factorial of: “;
cin >> nTarget;
// start with an accumulator that’s initialized to 1
int nAccumulator = 1;
int nValue = 1;
while (nValue <= nTarget)
{
cout << nAccumulator << “ * “
<< nValue << “ equals “;
nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
nValue++;
}
// display the result
cout << nTarget << “ factorial is “
<< nAccumulator << endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The program starts by prompting the user for a target value. The program readsthis value into nTarget. The program then initializes both nAccumulatorand nValue to 1 before entering the loop.(Pay attention — this is the interesting part.) The program compares nValueto nTarget. Assume that the user had entered a target value of 5. On thefirst loop, the question becomes, “Is 1 less than or equal to 5?” The answer is
Chapter 9: while Running in Circles 101obviously true, so control flows into the loop. The program outputsthe value of nAccumulator (1) and nValue (also 1) before multiplyingnAccumulator by nValue and storing the result back into nAccumulator.The last statement in the loop increments nValue from 1 to 2.That done, control passes back up to the while statement where nValue(now 2) is compared to nTarget (still 5). “Is 2 less than or equal to 5?”Clearly, yes; so control flows back into the loop. nAccumulator is now set tothe result of nAccumulator (1) times nValue (2). The last statement increments nValue to 3.This cycle of fun continues until nValue reaches the value 6, which is nolonger less than or equal to 5. At that point, control passes to the first statement beyond the closed brace }. This is shown graphically in Figure 9-1.Figure 9-1:Controlcontinues
to cycle
through
the body of
a whileloop untilthe conditional
expression
evaluates tofalse.while (nValue <= nTarget){
cout << nAccumulator << " * "
<< nValue << " equals ";
nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
nValue++;
}For nValue <= nTarget is truewhile (nValue <= nTarget)
| { | cout << nAccumulator << " * "For nValue <= nTarget is false |
cout << nAccumulator << endl;
nValue++;
}The actual output from the program appears as follows for an input value of 5:This program calculates factorial.Enter a number to take factorial of: 51 * 1 equals 11 * 2 equals 2
2 * 3 equals 6
6 * 4 equals 24
24 * 5 equals 120
5 factorial is 120
Press any key to continue . . .
102 Part III: Becoming a Functional ProgrammerYou are not guaranteed that the code within the braces of a while loop isexecuted at all: If the conditional expression is false the first time it’s evaluated, control passes around the braces without ever diving in. Consider, for
example, the output from the Factorial program when the user enters a target
value of 0:This program calculates factorial.Enter a number to take factorial of: 0
0 factorial is 1
Press any key to continue . . .No lines of output are generated from within the loop because the condition“Is nValue less than or equal to 0” was false even for the initial value of 1.The body of the while loop was never executed.Breaking out of the Middle of a LoopSometimes the condition that causes you to terminate a loop doesn’t occuruntil somewhere in the middle of the loop. This is especially true when testing user input for some termination character. C++ provides these two control commands to handle this case:✓ break exits the inner most loop immediately.✓ continue passes control back to the top of the loop.The following Product program demonstrates both break and continue.This program multiplies positive values entered by the user until the user
enters a negative number. The program ignores zero.//// Product - demonstrate the use of break and continue.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter the number to calculate the factorial of
cout << “This program multiplies the numbers\n”
<< “entered by the user. Enter a negative\n”
<< “number to exit. Zeroes are ignored.\n”
<< endl;
int nProduct = 1;
while (true)
{
Chapter 9: while Running in Circles 103int nValue;cout << “Enter a number to multiply: “;
cin >> nValue;
if (nValue < 0)
{
cout << “Exiting.” << endl;
break;
}
if (nValue == 0)
{
cout << “Ignoring zero.” << endl;
continue;
}
// multiply accumulator by this value and
// output the result
cout << nProduct << “ * “ << nValue;
nProduct *= nValue;
cout << “ is “ << nProduct << endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The program starts out with an initial value of nProduct of 1. The programthen evaluates the logical expression true to see if it’s true. It is.There aren’t too many rules that hold in C++ without exception, but here’s
one: true is always true.The program then enters the loop to prompt the user for another value to
multiply times nProduct, the accumulated product of all numbers enteredso far. If the value entered is negative, then the program outputs the phrase“Exiting.” before executing the break, which passes control out of the loop.If the value entered is not negative, control passes to the second if statement.If nValue is equal to zero, then the program outputs the messages “Ignoringzero.” before executing the continue statement which passes control backto the top of the loop to allow the user to enter another value.
If nValue is neither less than zero nor zero, then control flows down towhere nValue is multiplied by nProduct using the special assignment operator (see Chapter 4 if you don’t remember this one):nProduct *= nValue;104 Part III: Becoming a Functional ProgrammerThis expression is the same as:nProduct = nProduct * nValue;The output from a sample run from this program appears as follows:This program multiplies the numbersentered by the user. Enter a negative
number to exit. Zeroes are ignored.
Enter a number to multiply: 21 * 2 is 2Enter a number to multiply: 52 * 5 is 10Enter a number to multiply: 0Ignoring zero.Enter a number to multiply: 310 * 3 is 30Enter a number to multiply: -1Exiting.Press any key to continue . . .Why is “break” necessary?You might be tempted to wonder why break is really necessary. What if I had coded the loop in
the Product example program asint nProduct = 1;int nValue = 1;
while (nValue > 0)
{
cout << “Enter a number to multiply: “;
cin >> nValue;
cout << nProduct << “ * “ << nValue;
nProduct *= nValue;
cout << “ is “ << nProduct << endl;
}You might think that as soon as the user enters a negative value for nValue, the expressionnValue > 0 is no longer true and control immediately exits the loop — unfortunately, this is
not the case.
The problem is that the logical expression is only evaluated at the beginning of each pass through
the loop. Control doesn’t immediately fly out of the body of the loop as soon as the condition ceases
to be true. An if statement followed by a break allows me to move the conditional expression
into the body of the loop where the value of nValue is assigned.
Chapter 9: while Running in Circles 105
Nested LoopsThe body of a loop can itself contain a loop in what is known as nested loops. Theinner loop must execute to completion during each time through the outer loop.
I have created a program that uses nested loops to create a multiplication
table of the form:0 1 2 3 4 5 6 7 8 90 0*0 0*1 0*2 0*3 0*4 0*5 0*6 0*7 0*8 0*9
1 1*0 1*1 1*2 1*3 1*4 1*5 1*6 1*7 1*8 1*9
2 2*0 2*1 2*2 2*3 2*4 2*5 2*6 2*7 2*8 2*9
//... and so on...You can see that for row 0, the program will need to iterate from column 0through column 9. The program will repeat the process for row 1 and again for
row 2 and so on right down to row 9. This implies the need for two loops: an inner
loop to iterate over the columns and a second outer loop to iterate over the rows.
Each position in the table is simply the row number times the column number.
This is exactly how the following NestedLoops program works://// NestedLoops - this program uses a nested loop to
// calculate the multiplication table.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// display the column headings
int nColumn = 0;
cout << “ “;
while (nColumn < 10)
{
// set the display width to two characters
// (even for one digit numbers)
cout.width(2);
// now display the column number
cout << nColumn << “ “;
// increment to the next column
nColumn++;
}
cout << endl;
// now go loop through the rows
int nRow = 0;
106 Part III: Becoming a Functional Programmerwhile (nRow < 10){
// start with the row value
cout << nRow << “ - “;
// now for each row, start with column 0 and
// go through column 9
nColumn = 0;
while(nColumn < 10)
{
// display the product of the column*row
// (use 2 characters even when product is
// a single digit)
cout.width(2);
cout << nRow * nColumn << “ “;
// go to next column
nColumn++;
}
// go to next row
nRow++;
cout << endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The first section creates the column headings. This section initializes nColumnto 0. It then iterates through nColumn printing out its value separated bya space until nColumn reaches 10. At this point, the program exits the firstloop and then tacks a new line on the end to finish the row. This is shown
graphically in Figure 9-2.
Executing just this section alone generates the following output:0 1 2 3 4 5 6 7 8 9This program demonstrates an unfair advantage that I have. The expressioncout.width(2) sets the display width to two columns — C++ will pad aspace on the left for single-digit numbers. I know it’s cheating to make use of
a feature that I don’t present to the reader until Chapter 31, but it’s very difficult to get the columns to line up without resorting to fixed-width output.
The second set of loops, the nested loops, starts at nRow equal to 0. The program prints out the row number followed by a dash before launching into aChapter 9: while Running in Circles 107second loop that starts nColumn at 0 again and iterates it back up to 9. Foreach pass through this inner loop, the program sets the output width to two
spaces and then displays nRow * nColumn followed by a space.Figure 9-2:The firstloop outputs
the column
headings.// display the column headingsint nColumn = 0;
while (nColumn < 10)
{
// now display the column number
cout << nColumn << " ";
// increment to the next column
nColumn++;
}
//go to the next row
cout << end1;Output: 0 1 2 3 4 5 6 7 8 9The display width resets itself each time you output something, so it’s necessary to set it back to two each time before outputting a number.The program outputs a newline to move output to the next row each time it
increments nRow. This is shown graphically in Figure 9-3.The output from this program appears as follows:0 1 2 3 4 5 6 7 8 90 - 0 0 0 0 0 0 0 0 0 0
1 - 0 1 2 3 4 5 6 7 8 9
2 - 0 2 4 6 8 10 12 14 16 18
3 - 0 3 6 9 12 15 18 21 24 27
4 - 0 4 8 12 16 20 24 28 32 36
5 - 0 5 10 15 20 25 30 35 40 45
6 - 0 6 12 18 24 30 36 42 48 54
7 - 0 7 14 21 28 35 42 49 56 63
8 - 0 8 16 24 32 40 48 56 64 72
9 - 0 9 18 27 36 45 54 63 72 81
Press any key to continue . . .There is nothing magic about 0 through 9 in this table. I could just have easilycreated a 12 x 12 multiplication table (or any other combination) by changing
the comparison expression in the three while loops. However, for anythinglarger than 10 x 10, you will need to increase the minimum width to accommodate the three-digit products. Use cout.width(3).108 Part III: Becoming a Functional ProgrammerFigure 9-3:The innerloop iterates
from left to
right across
the columns, while
the outer
loop iterates
from top
to bottom
down the
rows.// now go loop through the rows
int nRow = 0;
while (nRow < 10)
{
// start with the row value
cout << nRow << " – ";
// now for each row, start with column 0 and
// go through column 9
nColumn = 0;
while(nColumn < 10)
{
cout << nRow * nColumn << " ";
// go to next column
nColumn++;
}
// go to next row
nRow++;
cout << end1;
}0 * 0 0 * 1 0 * 2 0 * 3 0 * 4 0 * 5 0 * 6 0 * 7 0 * 8 0 * 9
1 * 0 1* 1 1 * 2 1 * 3 1 * 4 1 * 5 1 * 6 1 * 7 1 * 8 1 * 9
2 * 0 2 * 1 2 * 2 2 * 3 2 * 4 2 * 5 2 * 6 2 * 7 2 * 8 2 * 9Output:Inner loop
Outer
loop
Chapter 10Looping for the Fun of ItIn This Chapter▶ Introducing the for loop▶ Reviewing an example ForFactorial program▶ Using the comma operator to get more done in a single for loopThe most basic of all control structures is the topic of Chapter 9. This chapter introduces you its sibling, the while loop, which is the for loop.Though not quite as flexible, the for loop is actually the more popular of thetwo — it has a certain elegance that is hard to ignore.The for Parts of Every LoopIf you look again at the examples in Chapter 9, you’ll notice that most loopshave four essential parts. (This feels like breaking down a golf swing into its
constituent parts.)✓ The setup: Usually the setup involves declaring and initializing anincrement variable. This generally occurs immediately before thewhile.✓ The test expression: The expression within the while loop that willcause the program to either execute the loop or exit and continue
on. This always occurs within the parentheses following the keywordwhile.✓ The body: This is the code within the braces.✓ The increment: This is where the increment variable is incremented.This usually occurs at the end of the body.
In the case of the Factorial program, the four parts looked like this:int nValue = 1; // the setupwhile (nValue <= nTarget) // the test expression
{ // the body
cout << nAccumulator << “ * “
110 Part III: Becoming a Functional Programmer<< nValue << “ equals “;nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
nValue++; // the increment
}The for loop incorporates these four parts into a single structure using thekeyword for:for(setup; test expression; increment){
body;
}The flow is shown graphically in Figure 10-1.1. As the CPU comes innocently upon the for keyword, control is divertedto the setup clause.2. Once the setup has been performed, control moves over to the testexpression.3. (a) If the test expression is true, control passes to the body of thefor loop.(b) If the test expression is false, control passes to the next statement after the closed brace.4. Once control has passed through the body of the loop, the CPU is forced
to perform a U-turn back up to the increment section of the loop.That done, control returns to the test expression and back to Step 3.Figure 10-1:The flow inand around
the forloop.for(setup; test expression; increment)
| { | 3a - if test expression is true3b - if test expression is |
| falsebody; |
5
Chapter 10: Looping for the Fun of It 111This for loop is completely equivalent to the following while loop:setup;while(test expression)
{
body;
increment;
}Looking at an ExampleThe following example program is the Factorial program written as a for loop(this program appears on the enclosed CD-ROM as ForFactorial)://// ForFactorial - calculate factorial using the for
// construct.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter the number to calculate the factorial of
int nTarget;
cout << “This program calculates factorial.\n”
<< “Enter a number to take factorial of: “;
cin >> nTarget;
// start with an accumulator that’s initialized to 1
int nAccumulator = 1;
for(int nValue = 1; nValue <= nTarget; nValue++)
{
cout << nAccumulator << “ * “
<< nValue << “ equals “;
nAccumulator = nAccumulator * nValue;
cout << nAccumulator << endl;
}
// display the result
cout << nTarget << “ factorial is “
112 Part III: Becoming a Functional Programmer<< nAccumulator << endl;// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The logic of this ForFactorial program is virtually identical to its olderFactorial twin: The program prompts the user to enter a number to take the
factorial of. It then initializes nAccumulator to 1 before entering the loopthat calculates the factorial.
ForFactorial creates an increment variable, nValue, that it initializes to 1in the setup clause of the for statement. That done, the program comparesnValue to nTarget, the value entered by the user in the test expressionsection of the for. If nValue is less than or equal to nTarget, control entersthe body of the loop where nAccumulator is multiplied by nValue.That done, control flows back up to the increment section of the for loop.This expression, nValue++, increments nValue by 1. Flow then moves tothe test expression, where nValue is compared with nTarget and theprocess repeated until eventually nValue exceeds the value of nTarget. Atthat point, control passes to the next statement after the closed brace.
The output from this program appears as follows:This program calculates factorials of user input.Enter a negative number to exit
Enter number: 5
5 factorial is 120
Enter number: 6
6 factorial is 720
Enter number: -1
Press any key to continue . . .All four sections of the for loop are optional. An empty setup, body, orincrement section has no effect; that is, it does nothing. (That makes sense.)An empty test expression is the same as true. (This is the only thing thatwould make sense — if it evaluated to false, then the body of the for loopwould never get executed, and the result would be useless.)
A variable defined within the setup section of a for loop is only defined withinthe for loop. It is no longer defined once control exits the loop.Chapter 10: Looping for the Fun of It 113
Getting More Done with
the Comma OperatorThere is a seemingly useless operator that I haven’t mentioned (up until now,that is) known as the comma operator. It appears as follows:expression1, expression2;This says execute expression1 and then execute expression2. The resultingvalue and type of the overall expression is the same as that of expression2.Thus, I could say something like the following:int i;int j;
i = 1, j = 2;Why would I ever want to do such a thing, you ask? Answer: You wouldn’texcept when writing for loops.The following CommaOperator program demonstrates the comma operator in
combat. This program calculates the products of pairs of numbers. If the operator enters N, the program outputs 1 * N, 2 * N-1, 3 * N-2, and so on, all the
way up to N * 1. (This program doesn’t do anything particularly useful. You’ll
see the comma operator used to effect when discussing arrays in Chapter 15.)//// CommaOperator - demonstrate how the comma operator
// is used within a for loop.
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter a target number
int nTarget;
cout << “Enter maximum value: “;
cin >> nTarget;
114 Part III: Becoming a Functional Programmerfor(int nLower = 1, nUpper = nTarget;nLower <= nTarget; nLower++, nUpper--)
{
cout << nLower << “ * “
<< nUpper << “ equals “
<< nLower * nUpper << endl;
}
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}The program first prompts the operator for a target value, which is read intonTarget. It then moves to the for loop. However, this time not only do youwant to increment a variable from 1 to nTarget, you also want to decrementa second variable from nTarget down to 1.Here the setup clause of the for loop declares a variable nLower that it initializes to 1 and a second variable nTarget that gets initialized to nTarget.The body of the loop displays nLower, nUpper, and the product nLower* nTarget. The increment section increments nLower and decrementsnUpper.The output from the program appears as follows:Enter maximum value: 151 * 15 equals 152 * 14 equals 28
3 * 13 equals 39
4 * 12 equals 48
5 * 11 equals 55
6 * 10 equals 60
7 * 9 equals 63
8 * 8 equals 64
9 * 7 equals 63
10 * 6 equals 60
11 * 5 equals 55
12 * 4 equals 48
13 * 3 equals 39
14 * 2 equals 28
15 * 1 equals 15
Press any key to continue . . .
Chapter 10: Looping for the Fun of It 115In this example run, I entered 15 as the target value. You can see how nLowerincrements in a straight line from 1 to 15, while nUpper makes its way from15 down to 1.
Actually, the output from this program is mildly interesting: No matter what
you enter, the value of the product increases rapidly at first as nLower increments from 1. Fairly quickly, however, the curve flattens out and asymptotically approaches the maximum value in the middle of the range beforeheading back down. The maximum value for the product always occurs whennLower and nUpper are equal.Could I have made the earlier for loop work without using the comma operator? Absolutely. I could have taken either variable, nLower or nUpper, out ofthe for loop and handled them as separate variables. Consider the followingcode snippet:nUpper = nTarget;for(int nLower = 1; nLower <= nTarget; nLower++)
{
cout << nLower << “ * “
<< nUpper << “ equals “
<< nLower * nUpper << endl;
nUpper--;
}This version would have worked just as well.The for loop can’t do anything that a while loop cannot do. In fact, any forloop can be converted into an equivalent while loop. However, because of itscompactness, you will see the for loop a lot more often.Up to and including this chapter, all of the programs have been one monolithic whole stretching from the opening brace after main() to the corresponding closing brace. This is okay for small programs, but it would bereally cool if you could divide your program into smaller bites that could be
digested separately. That is the goal of the next chapter on functions.
116 Part III: Becoming a Functional Programmer
Subscribe to:
Posts (Atom)
fuctional c++, arduino,etc
Chapter 11 Functions, I Declare! In This Chapter ▶ Breaking programs down into functions ▶ Writing and using functions ▶ Returning values fr...
-
C/C++ for Visual Studio Code (Preview) C/C++ support for Visual Studio Code is provided by a Microsoft C/C++ extension to enable cr...
-
udah lama ngga nge-blog nih.. jadi kangen posting sesuatu buat kalian :) adakah yang jam 00:36 WIB ini belum tidur? oke, kalo ada yang ...