[go: up one dir, main page]

0% found this document useful (0 votes)
41 views21 pages

CS101

Control structures allow programs to execute conditionally by altering the sequential flow of execution. There are three basic types of control structures: sequence, selection, and repetition. Selection structures like if and if/else allow a program to choose between alternative paths of execution based on a conditional test. Repetition structures like while and for allow a program to repeatedly execute a block of code as long as (or until) a condition remains true. Flowcharts can provide a graphical representation of an algorithm's control flow.

Uploaded by

sibghat ullah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views21 pages

CS101

Control structures allow programs to execute conditionally by altering the sequential flow of execution. There are three basic types of control structures: sequence, selection, and repetition. Selection structures like if and if/else allow a program to choose between alternative paths of execution based on a conditional test. Repetition structures like while and for allow a program to repeatedly execute a block of code as long as (or until) a condition remains true. Flowcharts can provide a graphical representation of an algorithm's control flow.

Uploaded by

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

Control Structures - I

Dr. Shahab Ansari


Control Structures
• Sequential execution
– Statements executed one after the other in the order written
• Transfer of control
– When the next statement executed is not the next one in sequence
• Bohm and Jacopini Theorem
– All programs written in terms of 3 control structures
• Sequence structure
– Built into C++. Programs executed sequentially by default.
• Selection structures
– C++ has three types - if, if/else, and switch
• Repetition structures
– C++ has three types - while, do/while, and for
Control Structures
• C++ keywords
– Cannot be used as identifiers or variable names.
C ++ Ke yw o rd s

Keywords common to the


C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
Control Structures
• Flowchart
– Graphical representation of an algorithm
– Drawn using certain special-purpose symbols connected by arrows
called flowlines.
– Rectangle symbol (action symbol)
• Indicates any type of action.
– Oval symbol
• indicates beginning or end of a program, or a section of
code (circles).
• single-entry/single-exit control structures
– Connect exit point of one control structure to entry point of the next
(control-structure stacking).
– Makes programs easy to build.
The if Selection Structure
• Selection structure
– used to choose among alternative courses of action
– Pseudocode example:
If student’s grade is greater than or equal to 60
Print “Passed”
– If the condition is true
• print statement executed and program goes on to next
statement
– If the condition is false
• print statement is ignored and the program goes onto the
next statement
– Indenting makes programs easier to read
• C++ ignores whitespace characters
The if Selection Structure
• Translation of pseudocode statement into C++:
if ( grade >= 60 )
cout << "Passed";
• Diamond symbol in flowcharts (decision symbol)
– indicates decision is to be made
– Contains an expression that can be true or false.
• Test the condition, follow appropriate path
 
• if structure is a single-entry/single-exit structure
The if Selection Structure
• Flowchart of pseudocode statement

A decision can be made


on any expression.
zero - false
true nonzero - true
grade >= 60 print “Passed”
Example:
3 - 4 is true
false
The if/else Selection Structure
• if
– Only performs an action if the condition is true
• if/else
– A different action is performed when condition is true and
when condition is false
• Psuedocode
if student’s grade is greater than or equal to 60
  print “Passed”
else
print “Failed”
• C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
The if/else Selection Structure

false true
grade >= 60

print “Failed” print “Passed”

• Ternary conditional operator (?:)


– Takes three arguments (condition, value if true, value if false)
• Our pseudocode could be written:
cout << ( grade >= 60 ? “Passed” :
“Failed” );

The if/else Selection Structure
Nested if/else structures
– Test for multiple cases by placing if/else selection structures inside
if/else selection structures.
if student’s grade is greater than or equal to 90
Print “A”
else
if student’s grade is greater than or equal to 80
Print “B”
else
if student’s grade is greater than or equal to 70
Print “C”
else
if student’s grade is greater than or equal
to 60
Print “D”
else
Print “F”
– Once a condition is met, the rest of the statements are skipped
The if/else Selection Structure
• Compound statement:
– Set of statements within a pair of braces
– Example:
if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
– Without the braces,
cout << "You must take this course again.\n";
would be automatically executed
• Block
– Compound statements with declarations
The if/else Selection Structure
• Syntax errors
– Errors caught by compiler
• Logic errors
– Errors which have their effect at execution time
• Non-fatal logic errors
– program runs, but has incorrect output

• Fatal logic errors


– program exits prematurely
Logical Operators
• && (logical AND)
– Returns true if both conditions are true
• || (logical OR)
– Returns true if either of its conditions are true
• ! (logical NOT, logical negation)
– Reverses the truth/falsity of its condition
– Returns true when its condition is false
– Is a unary operator, only takes one condition
• Logical operators used as conditions in loops
Expression Result
true && false false
true || false true
!false true
Confusing Equality (==) and Assignment (=) Operators
• These errors are damaging because they do not
ordinarily cause syntax errors.
– Recall that any expression that produces a value can be used in
control structures. Nonzero values are true, and zero values
are false
• Example:
if ( payCode == 4 )
cout << "You get a bonus!" << endl;
– Checks the paycode, and if it is 4 then a bonus is awarded
• If == was replaced with =
if ( payCode = 4 )
cout << "You get a bonus!" << endl;
– Sets paycode to 4
– 4 is nonzero, so the expression is true and a bonus is
awarded, regardless of paycode.
Confusing Equality (==) and Assignment (=)
Operators
• Lvalues
– Expressions that can appear on the left side of an equation
– Their values can be changed
– Variable names are a common example (as in x = 4;)
• Rvalues
– Expressions that can only appear on the right side of an equation
– Constants, such as numbers (i.e. you cannot write 4 = x;)
• Lvalues can be used as rvalues, but not vice versa
std::fixed, std::scientific
// modify floatfield
#include <iostream> // std::cout, std::fixed,
std::scientific
Possible output:
int main () { default:
double a = 3.1415926534; 3.1416
double b = 2006.0; 2006
double c = 1.0e-10; 1e-010

std::cout.precision(5); fixed:
3.14159
std::cout << "default:\n"; 2006.00000
std::cout << a << '\n' << b << '\n' << c << '\n'; 0.00000

std::cout << '\n'; scientific:


3.14159e+000
std::cout << "fixed:\n" << std::fixed; 2.00600e+003
std::cout << a << '\n' << b << '\n' << c << '\n'; 1.00000e-010

std::cout << '\n';

std::cout << "scientific:\n" << std::scientific;


std::cout << a << '\n' << b << '\n' << c << '\n';
return 0;
}
The switch Multiple-Selection Structure
• switch
– Useful when variable or expression is tested for multiple values
– Consists of a series of case labels and an optional default case

true
case a action(s) break
 
case a

false

true
case b case b action(s) break

false

.
.
.

true
case z case z action(s) break

false

default action(s)
1// Fig. 2.22: fig02_22.cpp

2// Counting letter grades

3#include <iostream>

5using std::cout;

6using std::cin;

7using std::endl;

9int main()

10 {

11 int grade, // one grade

12 aCount = 0, // number of A's

13 bCount = 0, // number of B's

14 cCount = 0, // number of C's

15 dCount = 0, // number of D's

16 fCount = 0; // number of F's

17

18 cout << "Enter the letter grades." << endl

19 << "Enter the EOF character to end input." << endl;

20

21 while ( ( grade = cin.get() ) != EOF ) {

22

23 switch ( grade ) {
Notice how the case statement is
// switch nested in while

24 used
25 case 'A': // grade was uppercase A

26 case 'a': // or lowercase a

27 ++aCount;

28 break; // necessary to exit switch

29

30 case 'B': // grade was uppercase B

31 case 'b': // or lowercase b

32 ++bCount;

33 break;

34
35 case 'C': // grade was uppercase C

36 case 'c': // or lowercase c

37 ++cCount;

38 break;

39

40 case 'D': // grade was uppercase D

41 case 'd': // or lowercase d break causes switch to end


42 ++dCount; and the program continues with the
43 break;
first statement after the switch
44

45 case 'F': // grade was uppercase F


structure.
46 case 'f': // or lowercase f

47 ++fCount;

48 break;

49

50 case '\n': // ignore newlines,

51 case '\t': // tabs,

52 case ' ': // and spaces in input


Notice the default statement.
53 break;

54

55 default: // catch all other characters

56 cout << "Incorrect letter grade entered."

57 << " Enter a new grade." << endl;

58 break; // optional

59 }

60 }

61

62 cout << "\n\nTotals for each letter grade are:"

63 << "\nA: " << aCount

64 << "\nB: " << bCount

65 << "\nC: " << cCount

66 << "\nD: " << dCount

67 << "\nF: " << fCount << endl;

68

69 return 0;

70 }
Enter the letter grades.
Enter the EOF character to end input.
a
B
c
C
A
d
f
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
b
 
Totals for each letter grade are:
A: 3
B: 2
C: 3
D: 2
F: 1
References
Dietal and Dietal : How to Program C++
3rd Edition

You might also like