Chapter 3
Chapter 3
Loops
&
Decisions
Animated Version
Chapter 3 - 1
Topics
• Relational Operators
• Loops
• Decisions
• Logical Operators
• Precedence Summary
• Other Control Statements
Chapter 3 - 2
Relational Operators
• A relational operator compares two values.
• The comparison involves such relationships as equal to, less than, and
greater than.
• The result of the comparison is true or false; for example, either two values
are equal (true), or they’re not (false).
// relat.cpp Output:
// demonstrates relational operators Enter a number: 20
#include <iostream> numb<10 is 0
using namespace std; numb>10 is 1
numb==10 is 0
int main()
{
int numb;
Note that:
The equal operator, ==,uses two equal signs. A common mistake is to use
a single equal sign—the assignment operator—as a relational operator.
This is a nasty bug, since the compiler may not notice anything wrong.
C++ generates a 1 to indicate true, it assumes that any value other than 0
(such as –7 or 44) is true; only 0 is false.
Chapter 3 - 4
Loops
Loops cause a section of your program to be repeated a certain number
of times. The repetition continues while a condition is true. When the
condition becomes false, the loop ends and control passes to the
statements following the loop.
three kinds of loops in C++: the for loop, the while loop, and the do
loop.
The For Loop:
The for loop executes a section of code a fixed number of times.
Basic Construction: for(j=0; j<15; j++)
Here, The for statement controls the loop. It consists of the keyword for,
followed by parentheses that contain three expressions separated by
semicolons.
These three expressions are the initialization expression, the test
expression, and the increment expression.
Chapter 3 - 5
Loops (2)
The Initialization Expression:
The initialization expression is executed only once, when the loop first starts. It gives the
loop variable an initial value
// cubelist.cpp
// lists cubes from 1 to 10
#include <iostream>
#include <iomanip> //for setw
using namespace std;
int main()
{
int numb; //define loop variable
Loops (3)
// factor.cpp
// calculates factorials, demonstrates FOR loop
#include <iostream>
using namespace std;
int main()
{
unsigned int numb;
unsigned long fact=1; -Variables
//long for larger numbersDefined in for
Statements
cout << "Enter a number: ";
cin >> numb; //get number decrements the loop
variable
for(int j=numb; j>0; j--) //multiply 1 by
fact *= j; //numb, numb-1, ..., 2, 1
cout << "Factorial is " << fact << endl;
return 0;
} Output:
Enter a number: 10
Factorial is 3628800
Chapter 3 - 8
Loops(4)
The While Loop:
The for loop does something a fixed number of
Times but While loop is used when you don’t know how many times you want to do
something before you start the loop.
The while loop looks like a simplified version of the for loop. It contains a test expression
but no initialization or increment expressions.
In a while loop, the test expression is evaluated at the beginning of the loop. If the test
expression is false when the loop is entered, the loop body won’t be executed at all.
Multiple statement is also used in while loop.
Output:
1
// endon0.cpp 27
// demonstrates WHILE loop 33
#include <iostream> 144
using namespace std; 9
int main() 0
{
int n = 99; // make sure n isn't
initialized to 0
Chapter 3 - 9
Loops (5)
// while4.cpp
// prints numbers raised to fourth power
#include <iostream>
#include <iomanip> //for setw
using namespace std;
int main()
{
int pow=1; //power initially 1
int numb=1; //numb goes from 1 to ???
int main()
{
long dividend, divisor;
char ch;
do //start of do loop
{ //do some processing
cout << "Enter dividend: "; cin >> dividend;
cout << "Enter divisor: "; cin >> divisor;
cout << "Quotient is " << dividend / divisor;
cout << ", remainder is " << dividend % divisor;
Output:
Enter dividend: 11
Enter divisor: 3
Quotient is 3, remainder is 2
Do another? (y/n): y
Enter dividend: 222
Enter divisor: 17
Quotient is 13, remainder is 1
Do another? (y/n): n
Chapter 3 - 11
Chapter 3 - 12
Decisions: The if Statement (1)
– The if statement is the simplest of the decision statements.
– The if keyword is followed by a test expression in parentheses
– the syntax of if is very much like that of while The difference is that the statements
following the if are executed only once if the test expression is true.
– You can nest ifs inside loops, loops inside ifs, ifs inside ifs, and so on.
// ifdemo.cpp
// demonstrates IF statement
#include <iostream>
using namespace std;
int main()
{
int x;
Chapter 3 - 13
// if2.cpp // prime.cpp
// demonstrates IF with multiline body // demonstrates IF statement with prime numbers
#include <iostream> #include <iostream>
using namespace std; using namespace std;
#include <process.h> //for exit()
int main()
{ int main()
int x; {
unsigned long n, j;
cout << "Enter a number: ";
cin >> x; cout << "Enter a number: ";
if( x > 100 ) cin >> n; //get number to
{ test
cout << "The number " << x; for(j=2; j <= n/2; j++) //divide by every
cout << " is greater than 100\n"; integer from
} if(n%j == 0) //2 on up; if
return 0; remainder is 0,
} { //it's divisible
by j
cout << "It's not prime; divisible by "
Output:
Enter a number: 12345 << j << endl;
The number 12345 is greater than 100 exit(0); //exit from the
program
}
Output:
cout << "It's prime\n"; Enter a number: 13
- causes the program to terminate, no return 0; It’s prime
} Enter a number: 22229
matter where it is in the listing. It’s prime
- argument is returned to the operating Enter a number: 22231
It’s not prime; divisible by 11
system when the program exits.
- 0: successful termination;
- other numbers: errors. Chapter 3 - 14
Decisions: The if...else Statement
– The if statement lets you do something if a condition is true. If it isn’t true, nothing
happens.
– But suppose we want to do one thing if a condition is true, and do something else if
it’s false. That’s where the if...else statement comes in.
– It consists of an if statement, followed by a statement or block of statements,
followed by the keyword else, followed by another statement or block of
statements.
// ifelse.cpp
// demonstrates IF...ELSE statememt
#include <iostream>
using namespace std;
int main()
{
int x;
Style Guide
if ( <boolean expression> ) {
…
} else {
…
Style 1
}
if ( <boolean expression> )
{
…
} Style 2
else
{
…
}
Chapter 3 - 16
Decisions: The if...else Statement (2)
• The getche() Library Function • With assignment expressions
- cin and >>: requires the user always press the // chcnt2.cpp
Enter key // counts characters and words typed in
#include <iostream>
- getche(): returns each character as soon as it’s using namespace std;
typed #include <conio.h> // for getche()
- requires the CONIO.H header file
int main()
- getch(): doesn’t echo the character to the screen {
int chcount=0;
int wdcount=1; // space between two words
// chcount.cpp char ch;
// counts characters and words typed in
#include <iostream> while( (ch=getche()) != '\r' ) // loop until Enter typed
using namespace std; {
#include <conio.h> //for getche() if( ch==' ' ) // if it's a space
wdcount++; // count a word
int main() else // otherwise,
{ chcount++; // count a character
int chcount=0; //counts non-space characters } // display results
int wdcount=1; //counts spaces between words cout << "\nWords=" << wdcount << endl
char ch = 'a'; //ensure it isn't '\r' << "Letters=" << chcount << endl;
return 0;
cout << "Enter a phrase: "; }
while( ch != '\r' ) //loop until Enter typed
Output:
{ Enter a number: 13
ch = getche(); //read one character It’s prime
if( ch==' ' ) //if it's a space Enter a number: 22229
wdcount++; //count a word It’s prime
else //otherwise, Enter a number: 22231
chcount++; //count a character It’s not prime; divisible by 11
} //display results
cout << "\nWords=" << wdcount << endl
<< "Letters=" << (chcount-1) << endl;
return 0;
} Output:
For while and do
Words=4
Letters=13 Chapter 3 - 17
int main()
{
char dir='a';
int x=10, y=10;
Chapter 3 - 18
Matching else
Are A and B different?
Chapter 3 - 19
int main()
clearer and easier to follow than
{
char dir='a';
the if...else approach.
int x=10, y=10;
int main()
{
int speed; //turntable speed
Chapter 3 - 21
int main()
{
char dir='a';
int x=10, y=10;
– switch statement:
» all the branches are selected by the same variable;
» the only thing distinguishing one branch from another is the value of this variable.
» The case constant must be an integer or character constant
» You cannot say:
Chapter 3 - 23
Conditional Operator
• consists of two symbols, which operate on three
operands
// condi.cpp
// prints 'x' every 8 columns
// demonstrates conditional operator
#include <iostream>
using namespace std;
int main()
{
for(int j=0; j<80; j++) //for every column,
True False { //ch is 'x' if
column is
char ch = (j%8) ? ' ' : 'x'; //multiple of 8,
and
cout << ch; //' ' (space)
otherwise
}
return 0;
}
Output:
x x x x x x x x x
Chapter 3 - 24
Logical Operators
• allow you to logically combine Boolean variables
• Logical AND Operator: // advenand.cpp
// demonstrates AND logical operator
#include <iostream>
using namespace std;
#include <process.h> //for exit()
#include <conio.h> //for getche()
int main()
{
char dir='a';
int x=10, y=10;
Chapter 3 - 25
Logical Operators
• Logical OR Operator: • The NOT Operator
– a unary operator—that is, it takes only one
// advenor.cpp
// demonstrates OR logical operator operand.
#include <iostream> – If something is true, ! makes it false; if it is false,
using namespace std;
#include <process.h> //for exit() ! makes it true.
#include <conio.h> //for getche()
int main()
{ • Precedence Summary
char dir='a';
int x=10, y=10;
Chapter 3 - 26
Other Control Statements
• The break Statement • The continue Statement
// showprim.cpp // divdo2.cpp
// displays prime number distribution // demonstrates CONTINUE statement
#include <iostream> #include <iostream>
using namespace std; using namespace std;
#include <conio.h> //for getche() Output:
int main() Enter dividend: 10
Enter divisor: 0
int main() {
Illegal divisor
{ long dividend, divisor; Enter dividend:
const unsigned char WHITE = 219; //solid color char ch;
(primes)
const unsigned char GRAY = 176; //gray (non primes) do {
unsigned char ch; cout << "Enter dividend: "; cin >> dividend;
//for each screen position cout << "Enter divisor: "; cin >> divisor;
for(int count=0; count<80*25-1; count++) if( divisor == 0 ) //if attempt to
{ { //divide by 0,
ch = WHITE; //assume it's prime cout << "Illegal divisor\n"; //display message
for(int j=2; j<count; j++) //divide by every continue; //go to top of
integer from loop
if(count%j == 0) //2 on up; if remainder is 0, }
{ cout << "Quotient is " << dividend / divisor;
ch = GRAY; //it's not prime cout << ", remainder is " << dividend % divisor;
break; //break out of inner
loop cout << "\nDo another? (y/n): ";
} cin >> ch;
cout << ch; //display the character } while( ch != 'n' );
} return 0;
getche(); //freeze screen until keypress }
return 0;
}
Chapter 2 - 27
Summary (1)
• Relational operators compare two values to see whether they’re equal,
whether one is larger than the other, and so on.
– The result is a logical or Boolean (type bool ) value, which is true or false.
– False is indicated by 0, and true by 1 or any other non-zero number.
• There are three kinds of loops in C++.
– The for loop is most often used when you know in advance how many times you
want to execute the loop.
– The while loop and do loops are used when the condition causing the loop to
terminate arises within the loop, with the while loop not necessarily executing at
all, and the do loop always executing at least once.
• A loop body can be a single statement or a block of multiple statements
delimited by braces. A variable defined within a block is visible only
within that block.
Chapter 3 - 28
Summary (2)
• There are four kinds of decision-making statements.
– The if statement does something if a test expression is true.
– The if...else statement does one thing if the test expression is true, and another
thing if it isn’t. The else if construction is a way of rewriting a ladder of nested
if...else statements to make it more readable.
– The switch statement branches to multiple sections of code, depending on the
value of a single variable.
– The conditional operator simplifies returning one value if a test expression is true,
and another if it’s false.
• Logiical operators:
– The logical AND and OR operators combine two Boolean expressions to yield
another one, and the logical NOT operator changes a Boolean value from true to
false, or from false to true.
• The break statement sends control to the end of the innermost loop or
switch in which it occurs.
• The continue statement sends control to the top of the loop in which it
occurs.
Chapter 3 - 29