2006 pearson education, inc. all rights reserved. 1 3 3 control statements: part 1: selection...
TRANSCRIPT
2006 Pearson Education, Inc. All rights reserved.
1
33Control Statements:
Part 1:Selection statements: if, if…else, switch
2006 Pearson Education, Inc. All rights reserved.
2
Control StatementsControl Statements
• Normally, statements in program are executed one after the other in the order in which they’re written.
• This is called sequential execution• Example: calculate area of rectangle.• There are control statements enable you to specify that the next one
in sequence.• This is called transfer of control.• The control statements are categorized in almost two groups: Selection control statements. Repetition control statements.
2006 Pearson Education, Inc. All rights reserved.
3
Control StructuresControl Structures
• Sequence structure– Programs executed sequentially by default
• Selection structures– if, if…else, switch
• Repetition structures– while, do…while, for
2006 Pearson Education, Inc. All rights reserved.
4
2006 Pearson Education, Inc. All rights reserved.
Sequential ExecutionSequential Execution
5
11
2
3
4
5
2006 Pearson Education, Inc. All rights reserved.
6
2006 Pearson Education, Inc. All rights reserved.
7
2006 Pearson Education, Inc. All rights reserved.
8
2006 Pearson Education, Inc. All rights reserved.
9
2006 Pearson Education, Inc. All rights reserved.
10
2006 Pearson Education, Inc. All rights reserved.
11
Fig. 3.1 | Equality and relational operators. Fig. 3.1 | Equality and relational operators.
Standard algebraic equality or relational operator
C++ equality or relational operator
Sample 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
2006 Pearson Education, Inc. All rights reserved.
12
Fig.3.2 | Arithmetic operators. Fig.3.2 | Arithmetic operators.
C++ operation C++ arithmetic operator
Algebraic expression
C++ expression
Addition + f + 7 f + 7
Subtraction - p – c p - c
Multiplication * bm or b· m b * m
Division / x / y or x
y or x ÷ y x / y
Modulus % r mod s r % s
2006 Pearson Education, Inc. All rights reserved.
If Selection StatementIf Selection Statement
• Condition– Expression can be either true or false– Can be formed using equality or relational
operators.
• if statement– If condition is true, body of the if statement
executes– If condition is false, body of the if statement
does not execute.
13
2006 Pearson Education, Inc. All rights reserved.
14
If Selection StatementIf Selection Statement
• Selection statements– Pseudocode example
• If student’s grade is greater than or equal to 60Print “Passed”– If the condition is true
» Print statement executes, program continues to next statement
– If the condition is false» Print statement ignored, program continues
2006 Pearson Education, Inc. All rights reserved.
If Selection StatementIf Selection Statement
15
Relational Expression
2006 Pearson Education, Inc. All rights reserved.
16
Arithmetic Expression
2006 Pearson Education, Inc. All rights reserved.
17
OutlineOutline
fig02_13.cpp
(1 of 2)
1 // Fig. 2.13: fig02_13.cpp
2 // Comparing integers using if statements, relational operators
3 // and equality operators.
4 #include <iostream> // allows program to perform input and output
5
6 using std::cout; // program uses cout
7 using std::cin; // program uses cin
8 using std::endl; // program uses endl
9
10 // function main begins program execution
11 int main()
12 {
13 int number1; // first integer to compare
14 int number2; // second integer to compare
15
16 cout << "Enter two integers to compare: "; // prompt user for data
17 cin >> number1 >> number2; // read two integers from user
18
19 if ( number1 == number2 )
20 cout << number1 << " == " << number2 << endl;
21
22 if ( number1 != number2 )
23 cout << number1 << " != " << number2 << endl;
24
25 if ( number1 < number2 )
26 cout << number1 << " < " << number2 << endl;
27
28 if ( number1 > number2 )
29 cout << number1 << " > " << number2 << endl;
30
using declarations eliminate need for std:: prefix
Can write cout and cin without std:: prefix
Declare variables
if statement compares values of number1 and number2 to test for equality
If condition is true (i.e., values are equal), execute this statementif statement compares values
of number1 and number2 to test for inequality
If condition is true (i.e., values are not equal), execute this statement
Compares two numbers using relational operator < and >
2006 Pearson Education, Inc. All rights reserved.
18OutlineOutline
fig02_13.cpp
(2 of 2)
fig02_13.cpp output (1 of 3)
(2 of 3)
(3 of 3)
31 if ( number1 <= number2 )
32 cout << number1 << " <= " << number2 << endl;
33
34 if ( number1 >= number2 )
35 cout << number1 << " >= " << number2 << endl;
36
37 return 0; // indicate that program ended successfully
38
39 } // end function main Enter two integers to compare: 3 7 3 != 7 3 < 7 3 <= 7 Enter two integers to compare: 22 12 22 != 12 22 > 12 22 >= 12 Enter two integers to compare: 7 7 7 == 7 7 <= 7 7 >= 7
Compares two numbers using relational operators <= and >=
2006 Pearson Education, Inc. All rights reserved.
19
Fig. 3.2 | Precedence and associativity of the operators discussed so far. Fig. 3.2 | Precedence and associativity of the operators discussed so far.
Operators Associativity Type
() left to right parentheses
* / % left to right multiplicative
+ - left to right additive
<< >> left to right stream insertion/extraction
< <= > >= left to right relational
== != left to right equality
= right to left assignment
2006 Pearson Education, Inc. All rights reserved.
20
Fig. 3.3 | C++ keywords.
C++ Keywords
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
and and_eq asm bitand Bitor bool catch class compl const_cast
delete dynamic_cast explicit export False
friend inline mutable namespace New not not_eq operator or or_eq
private protected public reinterpret_cast static_cast
template this throw true Try typeid typename using virtual wchar_t xor xor_eq
2006 Pearson Education, Inc. All rights reserved.
Selection Statements: IF Statements
Example:
Write a program that accept an integer from the user and in case integer is even print out the following message
• “This number is even”
21
2006 Pearson Education, Inc. All rights reserved.
Answer:22
2006 Pearson Education, Inc. All rights reserved.
• Important note:
• If (x==10)
• if (x=10)
• These expressions are not the same.
23
2006 Pearson Education, Inc. All rights reserved.
Selection Statement: IF Else Statement24
2006 Pearson Education, Inc. All rights reserved.
Selection Statement: IF Else Statement25
2006 Pearson Education, Inc. All rights reserved.
26
If…else Double-Selection Statement
• if– Performs action if condition true
• if…else– Performs one action if condition is true, a different action if it is false
• 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";
2006 Pearson Education, Inc. All rights reserved.
27
2006 Pearson Education, Inc. All rights reserved.
28
Example: Write a program that accept an integer from the user and print it is Positive or Negative number.
2006 Pearson Education, Inc. All rights reserved.
Answer29
2006 Pearson Education, Inc. All rights reserved.
30
IF…else Double-Selection Statement (Cont.)
• Ternary conditional operator (?:)– Three arguments (condition, value if true, value if false)
• Code could be written:– cout << ( grade >= 60 ? “Passed” : “Failed” );
Condition Value if true Value if false
2006 Pearson Education, Inc. All rights reserved.
Program of calculating the result of students
#include <iostream>
//#include <conio.h>
using namespace std;
int main()
{
int grade;
cout <<"enter the grade of the student \n";
cin>> grade;
if (grade>=60)
cout <<"Passed\n";
else
cout <<"Failed \n";
getchar();
return 0;
}
31
2006 Pearson Education, Inc. All rights reserved.
Nested IF32
2006 Pearson Education, Inc. All rights reserved.
33
Nested If
• Dangling-else problem– Compiler associates else with the immediately
preceding if– Example
• if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5";else cout << "x is <= 5“;
2006 Pearson Education, Inc. All rights reserved.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x, y;
cout<<“Enter any two numbers \n”;
cin>>x>>y;
if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5";else cout << "x is <= 5“;
getch();
}
34
2006 Pearson Education, Inc. All rights reserved.
Program of assigning a grade to students
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int studentGrade ;
cout<<“Enter the marks”;
cin>> studentGrade;
if ( studentGrade >= 90 ) cout << "A";else if (studentGrade >= 80 ) cout << "B";else if (studentGrade >= 70 ) cout << "C"; else if ( studentGrade >= 60 ) cout << "D";else cout << "F";
getch();
}
35
2006 Pearson Education, Inc. All rights reserved.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x, y;
cout<<“Enter any two numbers \n”;
cin>>x>>y;
if ( x > 5 ){ if ( y > 5 ) cout << "x and y are > 5";}else cout << "x is <= 5";
getch();
}
36
2006 Pearson Education, Inc. All rights reserved.
37
3.6 if…else Double-Selection Statement (Cont.)
• Dangling-else problem (Cont.)– Rewrite with braces ({})
• if ( x > 5 ){ if ( y > 5 ) cout << "x and y are > 5";else cout << "x is <= 5";
• }
– Braces indicate that the second if statement is in the body of the first and the else is associated with the first if statement
2006 Pearson Education, Inc. All rights reserved.
38
3.6 if…else Double-Selection Statement (Cont.)
• Compound statement– Also called a block
• Set of statements within a pair of braces• Used to include multiple statements in an if body
– Example• if ( studentGrade >= 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 executes
2006 Pearson Education, Inc. All rights reserved.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int grade;
cout<<“Enter grade \n”;
cin>>grade;
if ( studentGrade >= 60 ) cout << "Passed.\n";else { cout << "Failed.\n"; cout << "You must take this course again.\n";}
39
2006 Pearson Education, Inc. All rights reserved.
40
If-else if statement
• Also means to write an if statement within another if statement.
– One inside another, test for multiple cases – Once a condition met, other statements are skipped– Example
• 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”
2006 Pearson Education, Inc. All rights reserved.
IF- Else IF statement41
2006 Pearson Education, Inc. All rights reserved.
42
IF- Else IF statement (Cont.)
• Nested if…else statements (Cont.)
– Written In C++• if ( studentGrade >= 90 ) cout << "A";else if (studentGrade >= 80 ) cout << "B"; else if (studentGrade >= 70 ) cout << "C"; else if ( studentGrade >= 60 ) cout << "D"; else cout << "F";
2006 Pearson Education, Inc. All rights reserved.
Program of assigning a grade to students
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int marks;
cout<<“Enter the marks”;
cin>>marks;
if ( marks >= 90 ) cout << "A";else if (marks >= 80 ) cout << "B"; else if (marks >= 70 ) cout << "C"; else if ( marks >= 60 ) cout << "D"; else cout << "F";
getch();
}
43
2006 Pearson Education, Inc. All rights reserved.
44
IF- Else IF statement(Cont.)
• Nested if…else statements (Cont.)
– Written In C++ (indented differently)
• if ( studentGrade >= 90 ) cout << "A";else if (studentGrade >= 80 ) cout << "B";else if (studentGrade >= 70 ) cout << "C"; else if ( studentGrade >= 60 ) cout << "D";else cout << "F";
2006 Pearson Education, Inc. All rights reserved.
45
Logical Operators
• Logical operators– Allows for more complex conditions
• Combines simple conditions into complex conditions
• C++ logical operators– & (logical AND)
– | (logical OR)
– ! (logical NOT)
2006 Pearson Education, Inc. All rights reserved.
Logical Operators 46
2006 Pearson Education, Inc. All rights reserved.
47
2006 Pearson Education, Inc. All rights reserved.
48
2006 Pearson Education, Inc. All rights reserved.
49
Logical Operators (Cont.)
• Logical AND (&) Operator– Consider the following if statement
if (( gender == 1) & (age >= 65 ))
seniorFemales++;
– Combined condition is true • If and only if both simple conditions are true
– Combined condition is false • If either or both of the simple conditions are false
والشرط ) • األول الشرط الجزئين بفحص المترجم يقومالثاني(
2006 Pearson Education, Inc. All rights reserved.
50
Fig. 3.5| && (logical AND) operator truth table.
expression1 expression2 expression1 && expression2
false false false false true false true false false true true true
2006 Pearson Education, Inc. All rights reserved.
51
Logical Operators (Cont.)
• Logical OR (|) Operator– Consider the following if statement
if ( ( semesterAverage >= 90 ) |( finalExam >= 90 ))
cout << “Student grade is A” << endl;
– Combined condition is true • If either or both of the simple conditions are true
– Combined condition is false • If both of the simple conditions are false
2006 Pearson Education, Inc. All rights reserved.
52
Fig. 3.6 | || (logical OR) operator truth table.
expression1 expression2 expression1 || expression2
false false false false true true true false true true true true
2006 Pearson Education, Inc. All rights reserved.
53
Logical Operators (Cont.)
• Short-Circuit Evaluation of Complex Conditions– Parts of an expression containing && or || operators are
evaluated only until it is known whether the condition is true or false
– Example• (( gender == 1 ) && ( age >= 65 ))
– Stops immediately if gender is not equal to 1• Since the left-side is false, the entire expression must be false
األول • الجزء بفحص المترجم يقوم الحالة هذه في ) فحص) يتابع صحيحة قيمته كانت إذا األول الشرط
) قيمته ) كانت إذا أما ، الثاني الشرط الثاني الجزء. الثاني الجزء فحص في يواصل فال خطأ
2006 Pearson Education, Inc. All rights reserved.
Example54
2006 Pearson Education, Inc. All rights reserved.
Example55
2006 Pearson Education, Inc. All rights reserved.
What is the output?#include<iostream>
using namespace std;
int main()
{
int a=7;
int b=8;
if ((a>10) & (++b>7))
{
cout<<"that is right \n";
cout<<b;
}
return 0;
}
56
#include<iostream>
using namespace std;
int main()
{
int a=7;
int b=8;
if ((a>10) & (++b>7))
cout<<"that is right \n";
cout<<b;
return 0;
}
No output 9
#include<iostream>
using namespace std;
int main()
{
int a=7;
int b=8;
if ((a>10) & (++b>7))
cout<<"that is right \n";
cout<<b;
return 0;
}
8
2006 Pearson Education, Inc. All rights reserved.
What is the Output?57
#include<iostream>
using namespace std;
int main()
{
int x=5;
if (x=4)
cout<<“True \n";
else
cout<<“False \n”;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int x=5;
if (x==4)
cout<<“True \n";
else
cout<<“False \n”;
return 0;
}
Trueغير القيمة أن بما
صحيح فالشرط صفرالقاعدة حسب
False
#include<iostream>
using namespace std;
int main()
{
int x=5;
if (x=0)
cout<<“True \n";
else
cout<<“False \n”;
return 0;
}
Falseصفر القيمة أن بما
الشرط falseفسيعتبرالقاعدة حسب
2006 Pearson Education, Inc. All rights reserved.
What is the output for each program?
#include <iostream>
using namespace std;
int main()
{
int x, y;
x=7; y=10;
if ( x > 5 )
{if ( y > x ) cout << "x and y are > 5";
} else cout << "x is <= 5";
}
58
#include <iostream>
using namespace std;
int main()
{
int x, y;
X=4; y=10;
if ( x > 5 )
{if ( y > x )cout << "x and y are > 5";}else cout << "x is <= 5";
}
#include <iostream>
using namespace std;
int main()
{
int x, y;
X=7; y=5
if ( x > 5 )
{if ( y > x )cout << "x and y are > 5";}else cout << "x is <= 5";
}
x and y are > 5 x is <= 5 No output
2006 Pearson Education, Inc. All rights reserved.
59
Logical Operators (Cont.)
• Logical Negation (!) Operator– Unary operator
– Returns true when its operand is false, and vice versa
– Example• if ( !( grade == sentinelValue ) ) cout << "The next grade is " << grade << endl;is equivalent to:if ( grade != sentinelValue ) cout << "The next grade is " << grade << endl;
• Stream manipulator boolalpha– Display bool expressions in words, “true” or “false”
2006 Pearson Education, Inc. All rights reserved.
What is output?60
#include<iostream>
using namespace std;
int main()
{
int x=5;
if (!(x=4))
cout<<“True \n";
else
cout<<“False \n”;
return 0;
}
False
2006 Pearson Education, Inc. All rights reserved.
PART TWO
SWITCH STATEMENT
61
2006 Pearson Education, Inc. All rights reserved.
Selection Statements: Switch Statement
The switch control statement that allows us to make a decision from the number of choices.
• Expression: It could be an integer constant like 1,2 or 3, or an expression that evaluates to an integer.
• Constant: is a specific value.
62
2006 Pearson Education, Inc. All rights reserved.
Selection Statements: Switch Statement
63
32
2006 Pearson Education, Inc. All rights reserved.
Selection Statements: Switch Statement
64
2006 Pearson Education, Inc. All rights reserved.
Selection Statements: Switch Statement
65
2006 Pearson Education, Inc. All rights reserved.
Selection Statements: Switch Statement
66
Wrong:Case >=50Case a+b
2006 Pearson Education, Inc. All rights reserved.
67
switch Multiple-Selection Statement (Cont.)
• switch statement
– Controlling expression
• Expression in parentheses (أقواس)after keyword switch
– case labels
• Compared with the controlling expression
• Statements following the matching case label are executed
– Braces are not necessary around multiple statements in a case label
– A break statements causes execution to proceed (تمضي)with the first statement after the switch
• Without a break statement, execution will fall through to the next case label
2006 Pearson Education, Inc. All rights reserved.
68
switch Multiple-Selection Statement
•switch statement– Used for multiple selections
– Tests a variable or expression• Compared against constant integral expressions to decide on
action to take
– Any combination of character constants and integer constants that evaluates to a constant integer value
2006 Pearson Education, Inc. All rights reserved.
69
switch Multiple-Selection Statement (Cont.)
•switch statement (Cont.)– default case
• Executes if no matching case label is found
• Is optional
– If no match and no default case
• Control simply continues after the switch
2006 Pearson Education, Inc. All rights reserved.
Selection Statements: Switch Statement
70
للحرف الرقمية القيمة إختبار يتمعن عبارة ASCII CODEوهي
2006 Pearson Education, Inc. All rights reserved.
Selection Statements: Switch Statement71
2006 Pearson Education, Inc. All rights reserved.
What is the output#include<iostream>
using namespace std;
int main()
{
int i=20;
switch(i+10)
{
case 10:
cout<<"I am in level 1 \n"; break;
case 20:
cout<<"I am in level 2 \n"; break;
case 30:
cout<<"I am in level 3 \n“; break;
default:
cout<<"I am in default \n";
}
return 0;
}
72
I am in level 3
2006 Pearson Education, Inc. All rights reserved.
What is the output?#include<iostream>
using namespace std;
int main()
{
int i=20;
switch(i+10)
{
case 10:
cout<<"I am in level 1 \n"; //break;
case 20:
cout<<"I am in level 2 \n"; //break;
case 30:
cout<<"I am in level 3 \n“; //break;
default:
cout<<"I am in default \n";
}
return 0;
}
73
I am in level 1I am in level 2I am in level 3I am in default
2006 Pearson Education, Inc. All rights reserved.
74
2006 Pearson Education, Inc. All rights reserved.
Error in this switch expression 75
2006 Pearson Education, Inc. All rights reserved.
Error in case statement76
2006 Pearson Education, Inc. All rights reserved.
Error in case statement77
2006 Pearson Education, Inc. All rights reserved.
Error in case statement78
2006 Pearson Education, Inc. All rights reserved.
Can I apply this example for switch?79
NoBecause in this if example we put the condition between range.We can not put < or > in switch. We must put specific value.
2006 Pearson Education, Inc. All rights reserved.
Switch and If else
80
2006 Pearson Education, Inc. All rights reserved.
81
2006 Pearson Education, Inc. All rights reserved.
82
2006 Pearson Education, Inc. All rights reserved.
References
مراجع:
المحاضر محاضرات من أخذها تم شرائح هنالكالدسوقي إبراهيم محمد
Programming Basics For Beginners
83
2006 Pearson Education, Inc. All rights reserved.
End
84