KEMBAR78
Lec2. C++ Flow of Control | PDF | Boolean Data Type | Computer Data
0% found this document useful (0 votes)
43 views29 pages

Lec2. C++ Flow of Control

The document discusses different types of control flow statements in C++ including conditional statements like if/else and switch statements as well as loops like while, do-while and for loops. It provides syntax examples and explanations of how to use these statements. The document also covers concepts like break and continue in loops as well as nested loops.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views29 pages

Lec2. C++ Flow of Control

The document discusses different types of control flow statements in C++ including conditional statements like if/else and switch statements as well as loops like while, do-while and for loops. It provides syntax examples and explanations of how to use these statements. The document also covers concepts like break and continue in loops as well as nested loops.

Uploaded by

Majd AL Kawaas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter 2

Flow of Control

Copyright © 2017 Pearson Education, Ltd.


All rights reserved.
Boolean Expressions: Comparison Operators

• Logical Operators: Logical AND (&&) and Logical OR (||)

if ( (x = = 1) || (x = = y))
cout << "x is 1 or x equals y.\n";
else
cout << "x is neither 1 nor equal to y.\n";

2-2
Evaluating Boolean Expressions
• Data type bool
– Returns true or false
– true, false are predefined library consts

• Truth tables

2-3
Precedence of Operators
(1 of 2)

2-4
Precedence of Operators
(2 of 2)

2-5
Precedence Examples

• Arithmetic before logical


– x + 1 > 2 || x + 1 < -3 means:
• (x + 1) > 2 || (x + 1) < -3
• Short-circuit evaluation
– (x >= 0) && (y > 1)
– Be careful with increment operators!
• (x > 1) && (y++)

• Integers as boolean values


– All non-zero values  true
– Zero value  false

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-6


enum type
• enumeration type : type whose values are defined by a list of
constants of type and acts like an integer
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
• the default for the first enumeration constant is 0. The rest increase by 1 unless
you set one or more of the enumeration constants.

enum MonthLength { JAN_LENGTH = 31, FEB_LENGTH = 28, MAR_LENGTH = 31,


APR_LENGTH = 30, MAY_LENGTH = 31, JUN_LENGTH = 30, JUL_LENGTH = 31,
AUG_LENGTH = 31, SEP_LENGTH = 30, OCT_LENGTH = 31, NOV_LENGTH = 30,
DEC_LENGTH = 31 };

enum MyEnum { ONE = 17, TWO, THREE, FOUR = -3, FIVE };

ONE takes the value 17; TWO takes the next int value, 18; THREE takes the next
value, 19; FOUR takes -3; and FIVE takes the next value, -2.

2-7
#include <iostream>
using namespace std;
int main( )
{
enum Days {Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday };
Days day = Saturday;
if(day == Saturday)
cout << day << endl;
cout << Days::Sunday << endl;
cout << Friday << endl;
return 0;

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-8


Branching Mechanisms
• if-else statements
– Choice of two alternate statements based on condition expression
– Example:
if (hrs > 40)
grossPay = rate*40 + 1.5*rate*(hrs-40);
else
grossPay = rate*hrs;
• Formal syntax:
if (<boolean_expression>)
<yes_statement>
else
<no_statement>
• Note each alternative is only ONE statement!
• To have multiple statements execute in either branch  use
compound statement
2-9
Compound/Block Statement
• if-else statement Only "get" one statement per branch
• if-else statement Must use compound statement { } for multiples
– Also called a "block" stmt
• Each block should have block statement
– Even if just one statement
– Enhances readability

if (myScore > yourScore)


{
cout << "I win!\n";
wager = wager + 100;
}
else
{
cout << "I wish these were golf scores.\n";
wager = 0;
}

2-10
The Optional else: If you want "nothing" to happen in the false
branch, leave it out if (sales >= minimum)
salary = salary + bonus;
cout << "Salary = %" << salary;

– Note: nothing to do for false condition, so there is no else clause!


– Execution continues with cout statement

Nested Statements: if-else statements can also contain if-else stmt!


if (speed > 55)
if (speed > 80)
cout << "You’re really speeding!";
else
cout << "You’re speeding.";

2-11
Multiway if-else

The Boolean expressions are checked in order until the first true Boolean expression
is encountered, and then the corresponding statement is executed. If none of the
Boolean expressions is true, then the statement_For_All_Other_Possibilities is
2-12
executed.
The switch Statement
• A statement for controlling multiple branches
• Can do the same thing with if statements but sometimes switch is
more convenient
The controlling expression must always
return either a bool value, an enum
constant, one of the integer types, or a
char.

You need not place a break statement in


each case. If you omit a break, that case
continues until a break (or the end of the
switch statement) is reached.

2-13
The switch Statement in Action

2-14
The switch: multiple case labels
case 'A':
case 'a':
cout << "Excellent: you got an "A"!\n";
break;
case 'B':
case 'b':
cout << "Good: you got a "B"!\n";
break;

switch Menu Example


switch (response){
case 1:
// Execute menu option 1
break;
case 2:
// Execute menu option 2
break;
case 3:
// Execute menu option 3
break;
default:
cout << "Please enter valid response."; 2-15
}
Conditional Operator
• Also called "ternary operator"
– Allows embedded conditional in expression
– Essentially "shorthand if-else" operator
– Example: if (n1 > n2)
max = n1;
else
max = n2;

– Can be written:
max = (n1 > n2) ? n1 : n2;
• "?" and ":" form this "ternary" operator

2-16
Loops
• 3 Types of loops in C++
– while
• Most flexible
• No "restrictions"
– do-while
• Least flexible
• Always executes loop body at least once
– for
• Natural "counting" loop

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-17


while Loops Syntax

while (1)
{
cout << "Hello ";
}

count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}

2-18
Example of a while Statement

2-19
do-while Loop Syntax

count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition

2-20
Example of a do while Statement

2-21
for Loop Syntax

for (Init_Action; Bool_Exp; Update_Action)


Body_Statement

for (count=0;count<3;count++)
{
cout << "Hi "; // Loop Body
}

2-22
Loop Issues
• Loop’s condition expression can be ANY boolean expression
while (count<3 && done!=0)
{
// Do something
}
for (index=0;index<10 && entry!=-99)
{
// Do something
}

• Watch the misplaced ; Result here: INFINITE LOOP!

while (response != 0) ;
{
cout << "Enter val: ";
cin >> response;
}

2-23
#include <iostream> break: Forces loop to exit
using namespace std;
immediately
int main( ) {
int number, sum = 0, count = 0;
cout << "Enter 4 negative numbers:\n";
while (++count <= 4) {
cin >> number;
if (number >= 0){
cout << "ERROR: positive number"
<< " or zero was entered as the\n"
<< count << "th number! Input ends "
<< "with the " << count << "th number.\n"
<< count << "th number was not added in.\n";
break;
}
sum = sum + number;
}
cout << sum << " is the sum of the first "
<< (count - 1) << " numbers.\n";
return 0;
}

2-24
continue: Skips rest of loop body

2-25
Nested Loops
for (outer=0; outer<5; outer++)
for (inner=7; inner>2; inner--)
cout << outer << inner;

Copyright © 2017 Pearson Education, Ltd. All rights reserved. 2-26


Introduction to File Input
• We can read from a file in a way similar to reading from keyboard
• Opening a Text File
– Add at the top #include
<fstream>
– You can then declare an input stream just as
using you would declare any variable.
namespace
std;
ifstream inputStream;
– Next you must connect the inputStream variable to a text file on the disk.
inputStream.open("filename.txt");
– “filename.txt” is the pathname to a text file or a file in current directory
• Reading from a Text File
– Use inputStream >> var;
– Same as cin >> var except input is coming from text file and not keyboard
– When done with the file close it with inputStream.close();

2-27
File Input Example (2 of 2)
#include <iostream>
#include <fstream> Player.txt
#include <string> 100510
using namespace std; Gordon Freeman
int main( ) {
string firstName, lastName;
int score;
fstream inputStream;
inputStream.open("player.txt");
inputStream >> score;
inputStream >> firstName >> lastName;
cout << "Name: " << firstName << " "
<< lastName << endl;
cout << "Score: " << score << endl;
inputStream.close();
return 0;
}

2-28
File Input Example (2 of 2)
#include <iostream>
#include <fstream> Player.txt
#include <string> 100510
using namespace std; Gordon Freeman
int main( ) {
string text;
fstream inputStream;

inputStream.open("player.txt");
while (inputStream >> text)
{
cout << text << endl;
}
inputStream.close();
return 0;
}

2-29

You might also like