SlideShare a Scribd company logo
1 of 65
1
Control Structures
2
Flow chart
 Graphical representation of an algorithm or a portion of algorithm.
 Drawn using certain special-purpose symbols connected by arrows
called flow lines.
 Special purpose symbols.
Following are some symbols to draw a flow chart and there purpose.
Rectangles are action symbols to indicate any
type of action, including a calculation or an
input output operation.
Diamonds are conditional or decision symbols.
It indicates a decision to be made.
lozenges, ovals or rounded rectangles, indicate
start or end of the program usually containing
the word "Start, begin” or "End“.
3
Flow chart
Parallelogram are the input/output symbols
Arrows, showing what's called "
flow of control“. An arrow coming from
one symbol and ending at another
symbol represents that control passes to
the symbol the arrow points to. Arrows
are also called flow lines.
4
Control structures

Control structure
 A control statement and the statements whose execution it controls.
 a control statement is any statement that alters the linear flow of
control of a program. C++ examples include: if-else, while, for, break,
continue and return statement
 Sequential execution
 Statements executed in order
 Transfer of control
 Next statement to be executed may be other than the next one in
sequence.
5
Control structures
 Bohm and Jacopini’s control structures
Bohm and Jacopino’s work demonstrate that all programs could be written in
terms of only three control structures.
Sequence structures, selection structures and repetition structures.
 Sequence structure
 Built into C++. Programs executed sequentially by default.
 Selection structures

C++ has three types - if, if/else, and switch
6
Control structures
 if selection structure
. Perform an action if condition is true.
. Skip the action if condition is false.
 If/else selection structure
. Perform an action if condition is true.
. Performs a different action if the condition is false.
 switch selection structure
. Perform one of many different actions depending on the value of an
integer expression.
7
Control structures
 Repetition structures
 Many application require certain operations to be carried out more
than once. Such situations require repetition in control flow.
 C++ has three types while, do/while, for
 While selection structure
. An action to be repeated while some conditions remains true.
 Do/While selection structure
. Similar to while structure.
. Tests the loop continuation after the loop body is performed.
. while structure the loop continuation condition is tested at the beginning
of the loop before the body of loop is performed.
 We are going to discuss if and if/else selection structures first and
will explain the repetition structures and switch selection structure
latter. It was just an introduction to these structures.
8
Decision making structure/ selection structure
 Selection structure/decision structure
 allows the program to make a decision or comparison and then
select one of two paths, depending on the result of the comparison.
 Condition
 condition” is a logical expression that evaluates to true or false. It
could be a relational or Boolean expression. In other words
 Specifies the decision you are making
 Must result in either a true or false answer
 IF Structure
 One statement or a block of statement enclosed in braces {}
i.e. (compound statement), to be processed If condition met
otherwise it is skipped.

Uses equality and relational operators
9
Equality and relational operators
 Conditions in if structures can be formed by using the equality
and relational operators
 Equality operators
 Same level of precedence
 Associated left to right.
 Relational operators
 Same level of precedence.
 Associated left to right.
 Equality operators precedence is lower then precedence of
relational operators.
10
Equality and relational operators
Standard algebraic
equality operator or
relational operator
C++ equality
or relational
operator
Example
of C++
condition
Meaning of
C++ condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
≥ >= x >= y x is greater than or equal to y
≤ <= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
≠ != x != y x is not equal to y
11
Boolean Expressions
 Boolean expressions are expressions that are
either true or false
 comparison operators such as '>' (greater than)
are used to compare variables and/or numbers
 (grade >= 60) Including the parentheses, is the
boolean expression from the grade example
 A few of the comparison operators that use two
symbols (No spaces allowed between the symbols!)
 > greater than
 != not equal or inequality
 == equal or equivalent
 <= less than or equal to
etc
12
If selection structure
 The primary C++ selection structure statement used to
perform a single-alternative selection.
 Choose among alternative courses of action
 If the condition is true
 statement Print statement executed, program continues to
next
 If the condition is false
 Print statement ignored, program continues
13
If selection structure flow chart
14
If selection structure
 example:
Pseudocode
If student’s grade is greater than or equal to 60
Print “Passed”
C++ code
if ( grade >= 60 )
cout << "Passed";
15
If selection structure
 Flow chart for the pseudocode statement.
true
false
grade >= 60 print “Passed”
A decision can be made on
any expression.
16
Example
 Example is using the relational and equality operators.
 Following example used six if statements to compare two numbers
input by the user.
 If the condition in any of these if statements is satisfied, the
output statement associated with if is executed.
 If the condition with the if statement is false the output statement
associated with that if statement is skipped.
 Observe the different outputs for various inputs at the end of the
program.
17
1 // example
2 // Using if statements, relational
3 // operators, and equality operators
4 #include <iostream.h>
5
6
7
8
9
10 int main()
11 {
12 int num1, num2; // declare variables
13
14 cout << "Enter two integers, and I will tell youn"
15 << "the relationships they satisfy: ";
16 cin >> num1 >> num2; // read two integers
17
18 if ( num1 == num2 )
19 cout << num1 << " is equal to " << num2 << endl;
20
21 if ( num1 != num2 )
22 cout << num1 << " is not equal to " << num2 << endl;
23
24 if ( num1 < num2 )
25 cout << num1 << " is less than " << num2 << endl;
26
27 if ( num1 > num2 )
28 cout << num1 << " is greater than " << num2 << endl;
29
30 if ( num1 <= num2 )
31 cout << num1 << " is less than or equal to "
32 << num2 << endl; //continued on next slide
33
if structure compares values
of num1 and num2 to test for
equality.
If condition is true (i.e.,
values are equal), execute this
statement.if structure compares values
of num1 and num2 to test for
inequality.
If condition is true (i.e.,
values are not equal), execute
this statement.
If structure compare the
values of num1 and num2 to
test if num1 is less than num2
If condition is true (i.e., num1
is less than num2 ), execute
this statement.if structure compares values
of num1 and num2 to test if
num1 is greater than num2
If condition is true (i.e., num1
is greater than num2 ),
execute this statement.if structure compares values
of num1 and num2 to test if
num1 is less than or equal to
num2
If condition is true (i.e., num1
is less than or equal to num2),
execute this statement.
18
34 if ( num1 >= num2 )
35 cout << num1 << " is greater than or equal to "
36 << num2 << endl;
37
38 return 0; // indicate that program ended successfully
39 }
Input is 35 and 30
Input is 25 and 25
Input is 10 and 20
19
If/else selection structure
 Different actions if conditions true or false
 Syntax
 A single statement for each alternative
if (Boolean_expression)
yes_statement;
else
no_statement;
 A sequence statement for each alternative
if (Boolean_expression)
{ yes_statement1;
yes_statement2;
yes_statement last; }
else
{ no_statement1;
no_statement2;
no_statement last; }
20
If/else selection structure flow chart
Boolean expression
Action if false Action if true
truefalse
21
If/else selection structure
Example
 Pseudocode
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";
22
If/else selection structure
Flow chart for the pseudocode
truefalse
print “Failed” print “Passed”
grade >= 60
23
Compound Statement
 Compound statement
 Set of statements within a pair of braces also known as
BLOCK
if ( grade >= 60 )
cout << "Passed.n";
else {
cout << "Failed.n";
cout << "You must take this course again.n";
}
 Without braces,
cout << "You must take this course again.n";
always executed
24
Another simple Example
1. //program to determine if user is ill
2. #include <iostream>
3. using namespace std;
4. int main()
5. {
6. const double NORM = 98.6; // degree Fahranheit;
7. double temperature;
8. cout<<"Enter your temperaturet";
9. cin>>temperature;
10. if (temperature>NORM) //if temperature is greater than NORM print following statement
11. cout<<"nnYou are sickn"<<"take rest and drink lots of fluids";
12. else //if temperature is <= NORM print following statement
13. cout<<"nnYou are perfectly fine";
14. return 0;
15. }
25
output
Input is 100
100 > NORM
Input is 98
98<NORM
26
Example of if and if/else selection structure drawn in flow
chart form
If selection structure(program 1) If/else selection structure(program2)
27
c++ code for the flow chart of if selection structure
(program 1).
1. //program 1
2. //program to find the part prices for the given part number.
3. #include<iostream>
4. using namespace std;
5. int main()
6. {
7. int part_number, ;
8. float price;
9. cout<<"enter part number"<<endl;
10. cin>>part_number;
11. cout<<"enter price"<<endl;
12. cin>>price;
13. if(part_number==203)
14. price = price*1.1;
15. cout<<"price is "<<price;
16. return 0;
17. }
28
Output of program 1
Part_number is equal to 203
Part_number is not equal to 203
29
c++ code for the flow chart of if/else selection structure
(program 2).
 //program to calculate the sales commission
 #include <iostream>
 using namespace std;
 int main()
 {
 float sales, commission;
 cout<<"enter the sales"<<endl;
 cin>>sales;
 if (sales>1500)
 commission = sales*0.2;
 else
 commission = sales*0.1;
 cout<<"commission is"<<commission;

 return 0;
 }
30
Output of program 2
Sales is 1500
Sales is greater than 1500
31
Example of if/else
 Write a program to calculate the gross pay of an employee.
 The employee is paid at his basic hourly rate for the first 40 hours worked
during a week. Any hours worked beyond 40 is considered overtime.
 overtime is paid at the 1.5 times the hourly rate.
Pseudocode
If total number of hours >40
Gross pay = rate*40 + rate*1.5(hours – 40)
Else
Gross pay = rate * hours
32
C++ code
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int hour; //declaration
6. double gross_pay, rate;
7. cout<<"enter the hourly rate of payt"<<endl; //prompt
8. cin>>rate; //reading data
9. cout<<"enter the number of hours worked t"<<endl; //prompt
10. cin>>hour; //readin data
11. if(hour>40) //condition if working hours is greater than 40
12. gross_pay = rate*40 + 1.5*rate*(hour - 40); //gross pay including extra hour
13.
14. else //if working hour is <=40 then use this formula to get gross pay
15. gross_pay = rate*hour;
16.
17. cout<<" Gross pay is t"<<gross_pay<<endl; //printing the gross pay on screen.
18. return 0;
19. }
33
output
Hour<40
Hour>40
34
If/else selection structure
 Ternary conditional operator (?:)
 It is only ternary operator.
 It takes three operands together with conditional operator to form a
conditional expression
 Three arguments (condition, value if true, value if false)
 example
cout << ( grade >= 60 ? “Passed” : “Failed” );
 the value in the conditional can also be actions to execute for example
grade >= 60 ? cout << “Passed” : cout << “Failed” ;
Condition Value if true Value if false
35
Nested if/else structure
 if structure that rests entirely within another if structure,
within either the if or the else clause
 One inside another, test for multiple cases
 Once condition met, other statements skipped
36
Simple example to understand the nested if/else
 Consider an example of a program segment that accepts a gender
code and print gender according to that code.
 Pseudocode
if the gender code is F
print female
else
if the gender code is M
print male
else
print invalid code
37
Simple example to understand the nested if/else
 Flow chart
38
Simple example to understand the nested if/else
 C++ code
//F and M are correct codes
//f and m are invalid codes
39
Nested if/else structure
 following pseudocode is example of nested if/else
 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”
40
Nested if/else structure
C++ code
if ( grade >= 90 ) // 90 and above
cout << "A";
else
if ( grade >= 80 ) // 80-89
cout << "B";
else
if ( grade >= 70 ) // 70-79
cout << "C";
else
if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";
 if grade>=90, first four conditions will be true. But only the cout statement after the
first test will be executed. After that cout is executed, the else part of the outer
if/else statement is skipped.
41
Avoiding Common Pitfalls with if Statements
 Forgetting that C++ is case sensitive
 Assuming that indentation has a logical purpose
 Adding an unwanted semicolon
 Forgetting curly braces
 Using = instead of == (explained with example on next slide)
 Making unnecessary comparisons
42
Logical Operators
 Logical operators are used to combine more than one condition forming a complex
condition.
 Allow you to combine two or more conditions into one compound condition
 Data validation
 the process of verifying that the input data is within the expected
range
 C++ logical operators are
&& (Logical AND)
|| (Logical OR)
! (Logical NOT , logical negation)
43
Logical Operators
 && (Logical AND)
 All of the conditions must be true for the compound condition to be
true
 Syntax (Condition_1) && (Condition_2)
 True if both expressions are true
 Example
 if ( (2 < x) && (x < 7) )
 True only if x is between 2 and 7
 Inside parentheses are optional but enhance meaning
44
Logical Operators
 Be careful translating inequalities to C++
 if x < y < z translates as
if ( ( x < y ) && ( y < z ) )
NOT
if ( x < y < z )
45
Logical Operators
 || (Logical OR)
 only one of the conditions must be true for the compound condition to be true
 True if either or both expressions are true
 Syntax (Condition_1) || (Condition_2)
 Example
 if ( ( x = = 1) | | ( x = = y) )
 True if x contains 1
 True if x contains the same value as y
 True if both comparisons are true
46
Example to print hello according to user’s choice
Notice the program will print hello if input
Is upper case Y or lower case y
47
Output
Notice that program accepts both
Lowe case y and upper case Y
48
Logical Operators
 ! (Logical NOT , logical negation)
 Reverses the truth/falsity of its condition
 Returns true when its condition is false, & vice versa
 Is a unary operator, only takes one condition
 Example
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
Alternative
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;
49
Logical Operators
 ! negates any boolean expression
 !( x < y)
 True if x is NOT less than y
 !(x = = y)
 True if x is NOT equal to y
 ! Operator can make expressions difficult to understand…use only
when appropriate
Truth table for the ! (NOT, logical negation) operator
50
Confusing Equality (==) and Assignment (=) Operators
 Common error
 Does not typically cause syntax errors
 Aspects of problem
 Expressions that have a value can be used for decision
 Zero = false, nonzero = true
 Assignment statements produce a value (the value to be
assigned)
 = Assignment operator
 Used to assign values to variables
 X = 3
 == equality operator
 Used to compare values
 If (X == 3)
51
Confusing Equality (==) and Assignment (=) Operators
 Example
if ( payCode == 4 )
cout << "You get a bonus!" << endl;
 If paycode is 4, bonus given
 If == was replaced with =
if ( payCode = 4 )
cout << "You get a bonus!" << endl;
 Paycode set to 4 (no matter what it was before)
 Statement is true (since 4 is non-zero)
 Bonus given in every case
52
Confusing Equality (==) and Assignment (=) Operators
 L-values
 Expressions that can appear on left side of equation
 Can be changed (I.e., variables)
 x = 4;
 R-values
 Only appear on right side of equation
 Constants, such as numbers (i.e. cannot write 4 = x;)
 L-values can be used as R-values, but not vice versa
53
The switch Multiple-Selection Structure
 Switch is typically a selection structure and an alternative to the long
string of ifs
 Tests variables for multiple values
 Consists of a series of case labels and an optional default case
 General format
 switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch
case value2:
case value3: // taken if variable == value2 or == value3
statements
break;
default: // taken if variable matches no other cases
statements
break;
}
54
The switch Multiple-Selection Structure
 Expression (variable in braces after switch)
must be of type integer or character. It is the
controlling expression of switch statement
 The keyword case must be followed by a
constant
 break statement is required unless you want all
subsequent statements to be executed.
55
Reviewing character data type
 As we know a computers can process character data too
 char
 Short for character
 Can be any single character from the keyboard
 To declare a variable of type char:
char letter;
 Character constants are enclosed in single quotes
char letter = 'a';
 Strings of characters, even if only one character
is enclosed in double quotes
 "a" is a string of characters containing one character
 'a' is a value of type character
56
char   int
 It is possible to store char values in integer variables (an important feature of c++)
 Characters are represented as 1-byte integer in computers so we can treat a
character as either char or int depending on its use
int value = ‘A'; //65 is ASCII for A
 value will contain an integer representing 'A‘ i.e. value = 65
 Similarly
 It is possible to store int values in char variables
char letter = 97; //97 is numerical representation of lower case a (ASCII)
 Result of the above statement is letter = a
 Use single quotes to get numerical representation of a character
cout << "The character (" << 'a' << ") has the value "
<< ( int ) ( 'a' ) << endl;
Prints
The character (a) has the value 97
ASCII (American Standard Code For Information Interchange)
57
Comparing if/else with switch with the help of an example
•When you want to create
different outcomes
depending on specific
values, you can use a series
of ifs.
58
Comparing if/else with switch with the help of an example
 However, as an alternative to the long string of ifs, you can use the switch
statement
 Department is the control variable and is integer
 Compare the department to cases and prints the department it matches.
Removing break changes behavior of
statement.
It causes switch statement to end.
59
Example problem
 Problem statement
 Write a c++ program that enters the students grades
represented by letters A, B, C, D and F (program should
not be case sensitive)
 Use switch to count the number of each different letter
grades that the student earned on an exam
 Observe the flow chart on the next slide
60
Flow chart
true
false
.
.
.
case a case a action(s) break
case b case b action(s) break
false
false
case z case z action(s) break
true
true
default action(s)
61
C++ code
1 // grades are represented by letters
2 // Counting letter grades.
3 #include <iostream>
4
5
9 // function main begins program execution
10 int main()
11 {
int grade; // one grade
//initializing and declaring counters
13 int aCount = 0; // number of As
14 int bCount = 0; // number of Bs
15 int cCount = 0; // number of Cs
16 int dCount = 0; // number of Ds
17 int fCount = 0; // number of Fs
18
19 cout << "Enter the letter grades." << endl
20 << "Enter the EOF character to end input." << endl;
21
62
C++ code
22 // loop until user types end-of-file key sequence
23 while ( ( grade = cin.get() ) != EOF ) {
24
25 // determine which grade was input
26 switch ( grade ) { // switch structure nested in while
27
28 case 'A': // grade was uppercase A
29 case 'a': // or lowercase a
30 ++aCount; // increment aCount
31 break; // necessary to exit switch
32
33 case 'B': // grade was uppercase B
34 case 'b': // or lowercase b
35 ++bCount; // increment bCount
36 break; // exit switch
37
38 case 'C': // grade was uppercase C
39 case 'c': // or lowercase c
40 ++cCount; // increment cCount
41 break; // exit switch
42
cin.get() This function gets 1
character from the keyboard (after Enter
pressed), and it is assigned to grade.
Variable grade is the controlling
expression of switch. Value of grade is
compared with each of the case label
break causes switch to end and the
program continues with the first statement
after the switch structure.
If break is not used in switch structure each
time the match occur, statement for all
remaining cases will be executed.
Compares grade (an int) to the
numerical representations of A
and a.
cin.get() returns EOF (end-of-file) after the EOF
character is input, to indicate the end of data.
If the value assigned to grade is EOF the program
terminates.
EOF is symbolic integer constant defined in
<iostream> header file
EOF may be ctrl-d (UNIX) or ctrl-z (DOS, MS)
depending on your OS.
63
C++ code
43 case 'D': // grade was uppercase D
44 case 'd': // or lowercase d
45 ++dCount; // increment dCount
46 break; // exit switch
47
48 case 'F': // grade was uppercase F
49 case 'f': // or lowercase f
50 ++fCount; // increment fCount
51 break; // exit switch
52
53 case 'n': // ignore newlines,
54 case 't': // tabs,
55 case ' ': // and spaces in input
56 break; // exit switch
57
58 default: // catch all other characters
59 cout << "Incorrect letter grade entered."
60 << " Enter a new grade." << endl;
61 break; // optional; will exit switch anyway
62
63 } // end switch
64
65 } // end while
66
This test is necessary because
Enter is pressed after each
letter grade is input. This adds
a newline character that must
be removed. Likewise, we
want to ignore any
whitespace.
Notice the default statement, which
catches all other cases.
If no match occurs, the default case is
executed and an error message is
printed
64
C++ code
67 // output summary of results
68 cout << "nnTotals for each letter grade are:"
69 << "nA: " << aCount // display number of A grades
70 << "nB: " << bCount // display number of B grades
71 << "nC: " << cCount // display number of C grades
72 << "nD: " << dCount // display number of D grades
73 << "nF: " << fCount // display number of F grades
74 << endl;
75
76 return 0; // indicate successful termination
77
78 } // end function main
65
Output

More Related Content

What's hot

Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in cvampugani
 
Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C ProgrammingKamal Acharya
 
3. control statements
3. control statements3. control statements
3. control statementsamar kakde
 
Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 
C programming decision making
C programming decision makingC programming decision making
C programming decision makingSENA
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in CRAJ KUMAR
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statementsrajshreemuthiah
 
operators and control statements in c language
operators and control statements in c languageoperators and control statements in c language
operators and control statements in c languageshhanks
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators pptViraj Shah
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1Jomel Penalba
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrolsteach4uin
 
Selection statements
Selection statementsSelection statements
Selection statementsHarsh Dabas
 

What's hot (20)

Control structure
Control structureControl structure
Control structure
 
Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
 
Control structures i
Control structures i Control structures i
Control structures i
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C Programming
 
3. control statements
3. control statements3. control statements
3. control statements
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
C programming decision making
C programming decision makingC programming decision making
C programming decision making
 
Decision Making and Branching
Decision Making and BranchingDecision Making and Branching
Decision Making and Branching
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statements
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
operators and control statements in c language
operators and control statements in c languageoperators and control statements in c language
operators and control statements in c language
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrols
 
Selection statements
Selection statementsSelection statements
Selection statements
 

Similar to 03a control structures

C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c languagechintupro9
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Abou Bakr Ashraf
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionalish sha
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
Chapter 4.1
Chapter 4.1Chapter 4.1
Chapter 4.1sotlsoc
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Neeru Mittal
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner Huda Alameen
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
C Control Statements.docx
C Control Statements.docxC Control Statements.docx
C Control Statements.docxJavvajiVenkat
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and VariablesSyed Afaq Shah MACS CP
 
CIS 1403 lab 4 selection
CIS 1403 lab 4 selectionCIS 1403 lab 4 selection
CIS 1403 lab 4 selectionHamad Odhabi
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Blue Elephant Consulting
 

Similar to 03a control structures (20)

Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Ch05-converted.pptx
Ch05-converted.pptxCh05-converted.pptx
Ch05-converted.pptx
 
LOOPS AND DECISIONS
LOOPS AND DECISIONSLOOPS AND DECISIONS
LOOPS AND DECISIONS
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Chapter 4.1
Chapter 4.1Chapter 4.1
Chapter 4.1
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
C Control Statements.docx
C Control Statements.docxC Control Statements.docx
C Control Statements.docx
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
CIS 1403 lab 4 selection
CIS 1403 lab 4 selectionCIS 1403 lab 4 selection
CIS 1403 lab 4 selection
 
control structure
control structurecontrol structure
control structure
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1
 

More from Manzoor ALam

8085 microprocessor ramesh gaonkar
8085 microprocessor   ramesh gaonkar8085 microprocessor   ramesh gaonkar
8085 microprocessor ramesh gaonkarManzoor ALam
 
01 introduction to cpp
01   introduction to cpp01   introduction to cpp
01 introduction to cppManzoor ALam
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loopsManzoor ALam
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 

More from Manzoor ALam (6)

8085 microprocessor ramesh gaonkar
8085 microprocessor   ramesh gaonkar8085 microprocessor   ramesh gaonkar
8085 microprocessor ramesh gaonkar
 
01 introduction to cpp
01   introduction to cpp01   introduction to cpp
01 introduction to cpp
 
03b loops
03b   loops03b   loops
03b loops
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 

Recently uploaded

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 

Recently uploaded (20)

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 

03a control structures

  • 2. 2 Flow chart  Graphical representation of an algorithm or a portion of algorithm.  Drawn using certain special-purpose symbols connected by arrows called flow lines.  Special purpose symbols. Following are some symbols to draw a flow chart and there purpose. Rectangles are action symbols to indicate any type of action, including a calculation or an input output operation. Diamonds are conditional or decision symbols. It indicates a decision to be made. lozenges, ovals or rounded rectangles, indicate start or end of the program usually containing the word "Start, begin” or "End“.
  • 3. 3 Flow chart Parallelogram are the input/output symbols Arrows, showing what's called " flow of control“. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to. Arrows are also called flow lines.
  • 4. 4 Control structures  Control structure  A control statement and the statements whose execution it controls.  a control statement is any statement that alters the linear flow of control of a program. C++ examples include: if-else, while, for, break, continue and return statement  Sequential execution  Statements executed in order  Transfer of control  Next statement to be executed may be other than the next one in sequence.
  • 5. 5 Control structures  Bohm and Jacopini’s control structures Bohm and Jacopino’s work demonstrate that all programs could be written in terms of only three control structures. Sequence structures, selection structures and repetition structures.  Sequence structure  Built into C++. Programs executed sequentially by default.  Selection structures  C++ has three types - if, if/else, and switch
  • 6. 6 Control structures  if selection structure . Perform an action if condition is true. . Skip the action if condition is false.  If/else selection structure . Perform an action if condition is true. . Performs a different action if the condition is false.  switch selection structure . Perform one of many different actions depending on the value of an integer expression.
  • 7. 7 Control structures  Repetition structures  Many application require certain operations to be carried out more than once. Such situations require repetition in control flow.  C++ has three types while, do/while, for  While selection structure . An action to be repeated while some conditions remains true.  Do/While selection structure . Similar to while structure. . Tests the loop continuation after the loop body is performed. . while structure the loop continuation condition is tested at the beginning of the loop before the body of loop is performed.  We are going to discuss if and if/else selection structures first and will explain the repetition structures and switch selection structure latter. It was just an introduction to these structures.
  • 8. 8 Decision making structure/ selection structure  Selection structure/decision structure  allows the program to make a decision or comparison and then select one of two paths, depending on the result of the comparison.  Condition  condition” is a logical expression that evaluates to true or false. It could be a relational or Boolean expression. In other words  Specifies the decision you are making  Must result in either a true or false answer  IF Structure  One statement or a block of statement enclosed in braces {} i.e. (compound statement), to be processed If condition met otherwise it is skipped.  Uses equality and relational operators
  • 9. 9 Equality and relational operators  Conditions in if structures can be formed by using the equality and relational operators  Equality operators  Same level of precedence  Associated left to right.  Relational operators  Same level of precedence.  Associated left to right.  Equality operators precedence is lower then precedence of relational operators.
  • 10. 10 Equality and relational operators Standard algebraic equality operator or relational operator C++ equality or relational operator Example of C++ condition Meaning of C++ condition Relational operators > > x > y x is greater than y < < x < y x is less than y ≥ >= x >= y x is greater than or equal to y ≤ <= x <= y x is less than or equal to y Equality operators = == x == y x is equal to y ≠ != x != y x is not equal to y
  • 11. 11 Boolean Expressions  Boolean expressions are expressions that are either true or false  comparison operators such as '>' (greater than) are used to compare variables and/or numbers  (grade >= 60) Including the parentheses, is the boolean expression from the grade example  A few of the comparison operators that use two symbols (No spaces allowed between the symbols!)  > greater than  != not equal or inequality  == equal or equivalent  <= less than or equal to etc
  • 12. 12 If selection structure  The primary C++ selection structure statement used to perform a single-alternative selection.  Choose among alternative courses of action  If the condition is true  statement Print statement executed, program continues to next  If the condition is false  Print statement ignored, program continues
  • 14. 14 If selection structure  example: Pseudocode If student’s grade is greater than or equal to 60 Print “Passed” C++ code if ( grade >= 60 ) cout << "Passed";
  • 15. 15 If selection structure  Flow chart for the pseudocode statement. true false grade >= 60 print “Passed” A decision can be made on any expression.
  • 16. 16 Example  Example is using the relational and equality operators.  Following example used six if statements to compare two numbers input by the user.  If the condition in any of these if statements is satisfied, the output statement associated with if is executed.  If the condition with the if statement is false the output statement associated with that if statement is skipped.  Observe the different outputs for various inputs at the end of the program.
  • 17. 17 1 // example 2 // Using if statements, relational 3 // operators, and equality operators 4 #include <iostream.h> 5 6 7 8 9 10 int main() 11 { 12 int num1, num2; // declare variables 13 14 cout << "Enter two integers, and I will tell youn" 15 << "the relationships they satisfy: "; 16 cin >> num1 >> num2; // read two integers 17 18 if ( num1 == num2 ) 19 cout << num1 << " is equal to " << num2 << endl; 20 21 if ( num1 != num2 ) 22 cout << num1 << " is not equal to " << num2 << endl; 23 24 if ( num1 < num2 ) 25 cout << num1 << " is less than " << num2 << endl; 26 27 if ( num1 > num2 ) 28 cout << num1 << " is greater than " << num2 << endl; 29 30 if ( num1 <= num2 ) 31 cout << num1 << " is less than or equal to " 32 << num2 << endl; //continued on next slide 33 if structure compares values of num1 and num2 to test for equality. If condition is true (i.e., values are equal), execute this statement.if structure compares values of num1 and num2 to test for inequality. If condition is true (i.e., values are not equal), execute this statement. If structure compare the values of num1 and num2 to test if num1 is less than num2 If condition is true (i.e., num1 is less than num2 ), execute this statement.if structure compares values of num1 and num2 to test if num1 is greater than num2 If condition is true (i.e., num1 is greater than num2 ), execute this statement.if structure compares values of num1 and num2 to test if num1 is less than or equal to num2 If condition is true (i.e., num1 is less than or equal to num2), execute this statement.
  • 18. 18 34 if ( num1 >= num2 ) 35 cout << num1 << " is greater than or equal to " 36 << num2 << endl; 37 38 return 0; // indicate that program ended successfully 39 } Input is 35 and 30 Input is 25 and 25 Input is 10 and 20
  • 19. 19 If/else selection structure  Different actions if conditions true or false  Syntax  A single statement for each alternative if (Boolean_expression) yes_statement; else no_statement;  A sequence statement for each alternative if (Boolean_expression) { yes_statement1; yes_statement2; yes_statement last; } else { no_statement1; no_statement2; no_statement last; }
  • 20. 20 If/else selection structure flow chart Boolean expression Action if false Action if true truefalse
  • 21. 21 If/else selection structure Example  Pseudocode 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";
  • 22. 22 If/else selection structure Flow chart for the pseudocode truefalse print “Failed” print “Passed” grade >= 60
  • 23. 23 Compound Statement  Compound statement  Set of statements within a pair of braces also known as BLOCK if ( grade >= 60 ) cout << "Passed.n"; else { cout << "Failed.n"; cout << "You must take this course again.n"; }  Without braces, cout << "You must take this course again.n"; always executed
  • 24. 24 Another simple Example 1. //program to determine if user is ill 2. #include <iostream> 3. using namespace std; 4. int main() 5. { 6. const double NORM = 98.6; // degree Fahranheit; 7. double temperature; 8. cout<<"Enter your temperaturet"; 9. cin>>temperature; 10. if (temperature>NORM) //if temperature is greater than NORM print following statement 11. cout<<"nnYou are sickn"<<"take rest and drink lots of fluids"; 12. else //if temperature is <= NORM print following statement 13. cout<<"nnYou are perfectly fine"; 14. return 0; 15. }
  • 25. 25 output Input is 100 100 > NORM Input is 98 98<NORM
  • 26. 26 Example of if and if/else selection structure drawn in flow chart form If selection structure(program 1) If/else selection structure(program2)
  • 27. 27 c++ code for the flow chart of if selection structure (program 1). 1. //program 1 2. //program to find the part prices for the given part number. 3. #include<iostream> 4. using namespace std; 5. int main() 6. { 7. int part_number, ; 8. float price; 9. cout<<"enter part number"<<endl; 10. cin>>part_number; 11. cout<<"enter price"<<endl; 12. cin>>price; 13. if(part_number==203) 14. price = price*1.1; 15. cout<<"price is "<<price; 16. return 0; 17. }
  • 28. 28 Output of program 1 Part_number is equal to 203 Part_number is not equal to 203
  • 29. 29 c++ code for the flow chart of if/else selection structure (program 2).  //program to calculate the sales commission  #include <iostream>  using namespace std;  int main()  {  float sales, commission;  cout<<"enter the sales"<<endl;  cin>>sales;  if (sales>1500)  commission = sales*0.2;  else  commission = sales*0.1;  cout<<"commission is"<<commission;   return 0;  }
  • 30. 30 Output of program 2 Sales is 1500 Sales is greater than 1500
  • 31. 31 Example of if/else  Write a program to calculate the gross pay of an employee.  The employee is paid at his basic hourly rate for the first 40 hours worked during a week. Any hours worked beyond 40 is considered overtime.  overtime is paid at the 1.5 times the hourly rate. Pseudocode If total number of hours >40 Gross pay = rate*40 + rate*1.5(hours – 40) Else Gross pay = rate * hours
  • 32. 32 C++ code 1. #include <iostream> 2. using namespace std; 3. int main() 4. { 5. int hour; //declaration 6. double gross_pay, rate; 7. cout<<"enter the hourly rate of payt"<<endl; //prompt 8. cin>>rate; //reading data 9. cout<<"enter the number of hours worked t"<<endl; //prompt 10. cin>>hour; //readin data 11. if(hour>40) //condition if working hours is greater than 40 12. gross_pay = rate*40 + 1.5*rate*(hour - 40); //gross pay including extra hour 13. 14. else //if working hour is <=40 then use this formula to get gross pay 15. gross_pay = rate*hour; 16. 17. cout<<" Gross pay is t"<<gross_pay<<endl; //printing the gross pay on screen. 18. return 0; 19. }
  • 34. 34 If/else selection structure  Ternary conditional operator (?:)  It is only ternary operator.  It takes three operands together with conditional operator to form a conditional expression  Three arguments (condition, value if true, value if false)  example cout << ( grade >= 60 ? “Passed” : “Failed” );  the value in the conditional can also be actions to execute for example grade >= 60 ? cout << “Passed” : cout << “Failed” ; Condition Value if true Value if false
  • 35. 35 Nested if/else structure  if structure that rests entirely within another if structure, within either the if or the else clause  One inside another, test for multiple cases  Once condition met, other statements skipped
  • 36. 36 Simple example to understand the nested if/else  Consider an example of a program segment that accepts a gender code and print gender according to that code.  Pseudocode if the gender code is F print female else if the gender code is M print male else print invalid code
  • 37. 37 Simple example to understand the nested if/else  Flow chart
  • 38. 38 Simple example to understand the nested if/else  C++ code //F and M are correct codes //f and m are invalid codes
  • 39. 39 Nested if/else structure  following pseudocode is example of nested if/else  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”
  • 40. 40 Nested if/else structure C++ code if ( grade >= 90 ) // 90 and above cout << "A"; else if ( grade >= 80 ) // 80-89 cout << "B"; else if ( grade >= 70 ) // 70-79 cout << "C"; else if ( grade >= 60 ) // 60-69 cout << "D"; else // less than 60 cout << "F";  if grade>=90, first four conditions will be true. But only the cout statement after the first test will be executed. After that cout is executed, the else part of the outer if/else statement is skipped.
  • 41. 41 Avoiding Common Pitfalls with if Statements  Forgetting that C++ is case sensitive  Assuming that indentation has a logical purpose  Adding an unwanted semicolon  Forgetting curly braces  Using = instead of == (explained with example on next slide)  Making unnecessary comparisons
  • 42. 42 Logical Operators  Logical operators are used to combine more than one condition forming a complex condition.  Allow you to combine two or more conditions into one compound condition  Data validation  the process of verifying that the input data is within the expected range  C++ logical operators are && (Logical AND) || (Logical OR) ! (Logical NOT , logical negation)
  • 43. 43 Logical Operators  && (Logical AND)  All of the conditions must be true for the compound condition to be true  Syntax (Condition_1) && (Condition_2)  True if both expressions are true  Example  if ( (2 < x) && (x < 7) )  True only if x is between 2 and 7  Inside parentheses are optional but enhance meaning
  • 44. 44 Logical Operators  Be careful translating inequalities to C++  if x < y < z translates as if ( ( x < y ) && ( y < z ) ) NOT if ( x < y < z )
  • 45. 45 Logical Operators  || (Logical OR)  only one of the conditions must be true for the compound condition to be true  True if either or both expressions are true  Syntax (Condition_1) || (Condition_2)  Example  if ( ( x = = 1) | | ( x = = y) )  True if x contains 1  True if x contains the same value as y  True if both comparisons are true
  • 46. 46 Example to print hello according to user’s choice Notice the program will print hello if input Is upper case Y or lower case y
  • 47. 47 Output Notice that program accepts both Lowe case y and upper case Y
  • 48. 48 Logical Operators  ! (Logical NOT , logical negation)  Reverses the truth/falsity of its condition  Returns true when its condition is false, & vice versa  Is a unary operator, only takes one condition  Example if ( !( grade == sentinelValue ) ) cout << "The next grade is " << grade << endl; Alternative if ( grade != sentinelValue ) cout << "The next grade is " << grade << endl;
  • 49. 49 Logical Operators  ! negates any boolean expression  !( x < y)  True if x is NOT less than y  !(x = = y)  True if x is NOT equal to y  ! Operator can make expressions difficult to understand…use only when appropriate Truth table for the ! (NOT, logical negation) operator
  • 50. 50 Confusing Equality (==) and Assignment (=) Operators  Common error  Does not typically cause syntax errors  Aspects of problem  Expressions that have a value can be used for decision  Zero = false, nonzero = true  Assignment statements produce a value (the value to be assigned)  = Assignment operator  Used to assign values to variables  X = 3  == equality operator  Used to compare values  If (X == 3)
  • 51. 51 Confusing Equality (==) and Assignment (=) Operators  Example if ( payCode == 4 ) cout << "You get a bonus!" << endl;  If paycode is 4, bonus given  If == was replaced with = if ( payCode = 4 ) cout << "You get a bonus!" << endl;  Paycode set to 4 (no matter what it was before)  Statement is true (since 4 is non-zero)  Bonus given in every case
  • 52. 52 Confusing Equality (==) and Assignment (=) Operators  L-values  Expressions that can appear on left side of equation  Can be changed (I.e., variables)  x = 4;  R-values  Only appear on right side of equation  Constants, such as numbers (i.e. cannot write 4 = x;)  L-values can be used as R-values, but not vice versa
  • 53. 53 The switch Multiple-Selection Structure  Switch is typically a selection structure and an alternative to the long string of ifs  Tests variables for multiple values  Consists of a series of case labels and an optional default case  General format  switch ( variable ) { case value1: // taken if variable == value1 statements break; // necessary to exit switch case value2: case value3: // taken if variable == value2 or == value3 statements break; default: // taken if variable matches no other cases statements break; }
  • 54. 54 The switch Multiple-Selection Structure  Expression (variable in braces after switch) must be of type integer or character. It is the controlling expression of switch statement  The keyword case must be followed by a constant  break statement is required unless you want all subsequent statements to be executed.
  • 55. 55 Reviewing character data type  As we know a computers can process character data too  char  Short for character  Can be any single character from the keyboard  To declare a variable of type char: char letter;  Character constants are enclosed in single quotes char letter = 'a';  Strings of characters, even if only one character is enclosed in double quotes  "a" is a string of characters containing one character  'a' is a value of type character
  • 56. 56 char   int  It is possible to store char values in integer variables (an important feature of c++)  Characters are represented as 1-byte integer in computers so we can treat a character as either char or int depending on its use int value = ‘A'; //65 is ASCII for A  value will contain an integer representing 'A‘ i.e. value = 65  Similarly  It is possible to store int values in char variables char letter = 97; //97 is numerical representation of lower case a (ASCII)  Result of the above statement is letter = a  Use single quotes to get numerical representation of a character cout << "The character (" << 'a' << ") has the value " << ( int ) ( 'a' ) << endl; Prints The character (a) has the value 97 ASCII (American Standard Code For Information Interchange)
  • 57. 57 Comparing if/else with switch with the help of an example •When you want to create different outcomes depending on specific values, you can use a series of ifs.
  • 58. 58 Comparing if/else with switch with the help of an example  However, as an alternative to the long string of ifs, you can use the switch statement  Department is the control variable and is integer  Compare the department to cases and prints the department it matches. Removing break changes behavior of statement. It causes switch statement to end.
  • 59. 59 Example problem  Problem statement  Write a c++ program that enters the students grades represented by letters A, B, C, D and F (program should not be case sensitive)  Use switch to count the number of each different letter grades that the student earned on an exam  Observe the flow chart on the next slide
  • 60. 60 Flow chart true false . . . case a case a action(s) break case b case b action(s) break false false case z case z action(s) break true true default action(s)
  • 61. 61 C++ code 1 // grades are represented by letters 2 // Counting letter grades. 3 #include <iostream> 4 5 9 // function main begins program execution 10 int main() 11 { int grade; // one grade //initializing and declaring counters 13 int aCount = 0; // number of As 14 int bCount = 0; // number of Bs 15 int cCount = 0; // number of Cs 16 int dCount = 0; // number of Ds 17 int fCount = 0; // number of Fs 18 19 cout << "Enter the letter grades." << endl 20 << "Enter the EOF character to end input." << endl; 21
  • 62. 62 C++ code 22 // loop until user types end-of-file key sequence 23 while ( ( grade = cin.get() ) != EOF ) { 24 25 // determine which grade was input 26 switch ( grade ) { // switch structure nested in while 27 28 case 'A': // grade was uppercase A 29 case 'a': // or lowercase a 30 ++aCount; // increment aCount 31 break; // necessary to exit switch 32 33 case 'B': // grade was uppercase B 34 case 'b': // or lowercase b 35 ++bCount; // increment bCount 36 break; // exit switch 37 38 case 'C': // grade was uppercase C 39 case 'c': // or lowercase c 40 ++cCount; // increment cCount 41 break; // exit switch 42 cin.get() This function gets 1 character from the keyboard (after Enter pressed), and it is assigned to grade. Variable grade is the controlling expression of switch. Value of grade is compared with each of the case label break causes switch to end and the program continues with the first statement after the switch structure. If break is not used in switch structure each time the match occur, statement for all remaining cases will be executed. Compares grade (an int) to the numerical representations of A and a. cin.get() returns EOF (end-of-file) after the EOF character is input, to indicate the end of data. If the value assigned to grade is EOF the program terminates. EOF is symbolic integer constant defined in <iostream> header file EOF may be ctrl-d (UNIX) or ctrl-z (DOS, MS) depending on your OS.
  • 63. 63 C++ code 43 case 'D': // grade was uppercase D 44 case 'd': // or lowercase d 45 ++dCount; // increment dCount 46 break; // exit switch 47 48 case 'F': // grade was uppercase F 49 case 'f': // or lowercase f 50 ++fCount; // increment fCount 51 break; // exit switch 52 53 case 'n': // ignore newlines, 54 case 't': // tabs, 55 case ' ': // and spaces in input 56 break; // exit switch 57 58 default: // catch all other characters 59 cout << "Incorrect letter grade entered." 60 << " Enter a new grade." << endl; 61 break; // optional; will exit switch anyway 62 63 } // end switch 64 65 } // end while 66 This test is necessary because Enter is pressed after each letter grade is input. This adds a newline character that must be removed. Likewise, we want to ignore any whitespace. Notice the default statement, which catches all other cases. If no match occurs, the default case is executed and an error message is printed
  • 64. 64 C++ code 67 // output summary of results 68 cout << "nnTotals for each letter grade are:" 69 << "nA: " << aCount // display number of A grades 70 << "nB: " << bCount // display number of B grades 71 << "nC: " << cCount // display number of C grades 72 << "nD: " << dCount // display number of D grades 73 << "nF: " << fCount // display number of F grades 74 << endl; 75 76 return 0; // indicate successful termination 77 78 } // end function main