week selection c
TRANSCRIPT
-
8/3/2019 Week Selection C
1/110
SCK1213 Programming Technique ISEM1 2009/2010
Making Decisions
Week 7
Source from Tony Gaddis, Barret Krupnow, Starting out with C++, 5th editionupdate. 2007. Pearson Addison-Wesley
-
8/3/2019 Week Selection C
2/110
Selection structure
Selection will be chosen based onconditions
In C, there are 3 ways for selectionstructure:
1. Selection using if & else
if, expanding if, if/else, if/else if, trailing else, nested if
2. Selection using conditional operators
3. Selection using switch, case & break
-
8/3/2019 Week Selection C
3/110
Relational Operators & Logical
Operators
4.1
-
8/3/2019 Week Selection C
4/110
Relational Operators
Used to compare numbers to determinerelative order
Operators:
-
8/3/2019 Week Selection C
5/110
Logical Operators
Used to create relational expressions fromother relational expressions
Operators, meaning, and explanation:
&& AND New relational expression is true ifboth expressions are true
|| OR New relational expression is true if
either expression is true! NOT Reverses the value of an expression
true expression becomes false, andfalse becomes true
-
8/3/2019 Week Selection C
6/110
Logical data
Also called Boolean
In C, there is no True or False Value.
A Zero value is treated as False
A Non-Zero value is treated as True
True and False in arithmetic scale
-
8/3/2019 Week Selection C
7/110
Logical operators truth table
-
8/3/2019 Week Selection C
8/110
Relational expression T/F examples
-
8/3/2019 Week Selection C
9/110
The if Statement4.2
-
8/3/2019 Week Selection C
10/110
The if Statement
Allows statements to be conditionallyexecuted or skipped over
Models the way we mentally evaluatesituations:
"If it is raining, take an umbrella."
"If it is cold outside, wear a coat."
-
8/3/2019 Week Selection C
11/110
Flowchart for Evaluating a Decision
-
8/3/2019 Week Selection C
12/110
Flowchart for Evaluating a Decision
-
8/3/2019 Week Selection C
13/110
The if Statement
General Format:
if (expression)
statement;
-
8/3/2019 Week Selection C
14/110
if statement what happens
To evaluate:
if (expression)
statement;
If the expression is true, thenstatement is executed.
If the expressionis false, thenstatement is skipped.
-
8/3/2019 Week Selection C
15/110
if statement - example
-
8/3/2019 Week Selection C
16/110
if statement notes
Do not place ; after (expression)
Place statement; on a separate line
after (expression), indented:if (score > 90)
grade = 'A';
Be careful testing float and doublefor equality
0 is false; any other value is true
-
8/3/2019 Week Selection C
17/110
Flowchart if
-
8/3/2019 Week Selection C
18/110
Flowchart if with example
Printing a number only if it is smaller than 0
-
8/3/2019 Week Selection C
19/110
Exercise Week 7_1
Refer to Lab 7, Exe 2 No. 1 (i) in pg. 60.
Explain and draw the flowchart
-
8/3/2019 Week Selection C
20/110
Flags
4.3
-
8/3/2019 Week Selection C
21/110
Flags
Variable that signals a condition
Usually implemented as a bool variable
As with other variables in functions, mustbe assigned an initial value before it isused
-
8/3/2019 Week Selection C
22/110
Exercise Week 7_2 Trace the following programs if the input is 22 and 68
int main()
{
float mark;
bool pass=false; //this condition does not yet exist
printf ("Enter your mark");
scanf ("%f", &mark);
if (mark >=30)
pass=true;
if (pass)
printf ("You pass the test\n");
if (!pass)printf ("You fail the test\n");
printf ("Program end");
getch();
return 0;
}
-
8/3/2019 Week Selection C
23/110
Expanding the if Statement
4.4
-
8/3/2019 Week Selection C
24/110
Expanding the if Statement
To execute more than one statement as part ofan if statement, enclose them in { }:
if (score > 90)
{grade = 'A';
cout
-
8/3/2019 Week Selection C
25/110
Expanding the if Statement - example
-
8/3/2019 Week Selection C
26/110
Exercise Week 7_3 (Solve the problem)
Identify the logic errors, and correct them The program will display Pass message, calculate the carry mark anddisplay the carry mark if the student pass the test.
If the student fail the test the program will display Fail message and
display a message to instruct the student to re-sit the testint main()
{double mark, final20p = 0;
printf ("Enter your mark: ");
scanf ("%lf", &mark);
if (mark >= 30)
printf ("TEST 1 -> Pass\n");
final20p = ((20.0/100.0) * mark);
printf ("Contribution to final mark %ld", final20p);
if (mark < 30)
printf ("TEST 1 -> Fail\n");
printf ("Please re-sit TEST 1\n");
getch();
return 0;}
-
8/3/2019 Week Selection C
27/110
The if/else Statement
4.5
-
8/3/2019 Week Selection C
28/110
The if/else Statement
Provides two possible paths of execution
Performs one statement or block if the
expression is true, otherwise performsanother statement or block.
-
8/3/2019 Week Selection C
29/110
The if/else Statement
General Format:
if (expression)
statement1; // or block
else
statement2; // or block
-
8/3/2019 Week Selection C
30/110
if/else what happens
To evaluate:if (expression)
statement1;
else
statement2;
If the expression is true, then statement1is executed and statement2 is skipped.
If the expression is false, thenstatement1 is skipped and statement2 isexecuted.
-
8/3/2019 Week Selection C
31/110
if statement exampleif/else statement example
IF score is higher than 50
THEN grade is PASS
ELSE grade is FAIL
In C, this corresponds to if statement with three parts:
-
8/3/2019 Week Selection C
32/110
if statement exampleif statement condition
Part 1: the condition an expression thatis evaluated to TRUE or FALSE
-
8/3/2019 Week Selection C
33/110
if statement TRUE
Part 2: the TRUE-part a block ofstatements that are executed if thecondition evaluates to TRUE
-
8/3/2019 Week Selection C
34/110
else statement FALSE
Part 3: the FALSE-part a block ofstatements that are executed if thecondition evaluates to FALSE
If the conditionevaluates to FALSE,the TRUE-part isskipped
-
8/3/2019 Week Selection C
35/110
Flowchart if/else
-
8/3/2019 Week Selection C
36/110
if/else statement notes
If the TRUE-part (or FALSE-part) consists ofonly one statement, then the curly braces maybe omitted
E.g. these two statements are equivalent:
-
8/3/2019 Week Selection C
37/110
Flowchart 2 - if/else
Example: if two numbers (p and q) are equivalent, resetthem to zero, otherwise, exchange or swap their valueand then print the new values.
-
8/3/2019 Week Selection C
38/110
The three forms of if statements
The conditionisalways inparentheses
All TRUE-partsand all FALSE-parts are a singlestatement of a
block of code /compoundstatements
-
8/3/2019 Week Selection C
39/110
Exercise Week 7_4
Refer back to Lab 7, Exe 2, No. 1, pg. 60.
Solve the problem in (ii) and (iii) pg.61
-
8/3/2019 Week Selection C
40/110
The if/else if Statement
4.6
-
8/3/2019 Week Selection C
41/110
The if/else if Statement
Chain of if statements that test in order
until one is found to be true
Also models thought processes:
If it is raining, take an umbrella,
else, if it is windy, take a hat,else, take sunglasses
-
8/3/2019 Week Selection C
42/110
if/else if format
if (expression)
statement1; // or block
else if (expression)
statement2; // or block
.
. // other else ifs
.
else if (expression)
statementn; // or block
-
8/3/2019 Week Selection C
43/110
(ProgramContinues
)
if/else if format example program 7-12
//This program uses an if/else if statement to assign a//letter grade (A, B, C, D, or F) to a numeric test score.#include #include
int main(){
int testScore; //To hold a numeric test scorechar grade; //To hold a letter grade
//Get the numeric test scoreprintf ("Enter your numeric test score and I will\n");printf ("tell you the letter grade you earned: ");scanf ("%d", &testScore);
//Determine the letter gradeif (testScore < 60)
grade = 'F';else if (testScore < 70)
grade = 'D';else if (testScore < 80)
grade = 'C';else if (testScore < 90)
grade = 'B';
-
8/3/2019 Week Selection C
44/110
if/else if format - example
else if (testScore
-
8/3/2019 Week Selection C
45/110
Exercise Week 7_5
Refer to Lab 7, Exe 3, No. 1 in pg. 62.
Draw a flowchart for Program 7.3
Refer to Lab 7, Exe 3, No. 2 in pg. 62-63.
Draw a flowchart for Program 7.4
Discuss the differences.
-
8/3/2019 Week Selection C
46/110
Using a Trailing else
4.7
-
8/3/2019 Week Selection C
47/110
Using a Trailing else
Used with if/else if statement whennone of the expressions are true
Provides default statement/action Used to catch invalid values, other
exceptional situations
-
8/3/2019 Week Selection C
48/110
From Program 7-12
if (testScore < 60)
grade = 'F';
else if (testScore < 70)
grade = 'D';
else if (testScore < 80)
grade = 'C';
else if (testScore < 90)
grade = 'B';
else if (testScore
-
8/3/2019 Week Selection C
49/110
Flowchart with trailing else
-
8/3/2019 Week Selection C
50/110
Flowchart with trailing else
Example: identifying the grade of a score
-
8/3/2019 Week Selection C
51/110
Menus
4.8
-
8/3/2019 Week Selection C
52/110
Menus
Menu-driven program: program executioncontrolled by user selecting from a list of
actions Menu: list of choices on the screen
Menus can be implemented using
if/else if statements
-
8/3/2019 Week Selection C
53/110
Menu-driven program organization
Display list of numbered or lettered choicesfor actions
Prompt user to make selection Test user selection in expression
if a match, then execute code for action
if not, then go on to next expression
-
8/3/2019 Week Selection C
54/110
Exercise Week 7_6
Refer to Lab 7, Exe. 4, No. 1, Program 7.5. inpg. 63.
Use if / else.if to select the menu
Use trailing else to print We dont have
any
Jump to switch slide #93
-
8/3/2019 Week Selection C
55/110
Nested if Statements
4.9
-
8/3/2019 Week Selection C
56/110
Nested if Statements
An if statement that is part of the if orelse part of another if statement
Can be used to evaluate more than one
condition:if (score < 100) or,
{
if (score > 90)
grade = 'A';
}
condition1
condition2
condition3TRUE-part,
Nested if Statements Problem-solving
-
8/3/2019 Week Selection C
57/110
Nested if Statements Problem-solvingexample
Write a program to calculate and displayan area of a rectangle. Size of each side isgiven by a user from a keyboard. Your
program must ensure that the size of eachside is not zero or negative. If side is zero,display a warning message to the user
and turn the area into zero. If the sidegiven is negative, only take the magnitude.
Nested if Statements Problem-solving
-
8/3/2019 Week Selection C
58/110
Nested if Statements Problem-solvingexample
i) Problem analysisInput
media: keyboard
data: width and length
Output:media: screen
data: area of a rectangle
Process:
1. To find magnitude of a number:
if number is negative, magnitude = -(number)
if number is positive, magnitude = number
2. Area of a rectangle = width x length
Nested if Statements Problem-solving
-
8/3/2019 Week Selection C
59/110
Nested if Statements Problem-solvingexample
ii) Pseudo-code1. Read width & length from user
2. if width = 0 or length = 0, then
2.1 begin
2.1.1 print warning message
2.1.2 area = 02.2 end_if
3. else
3.1 begin
3.1.1 if negative length then
3.1.1.1 length = magnitudelength
3.1.2 end_if
3.1.3 if negative width, then
3.1.3.1 width = magnitude width
3.1.4 end_if
3.1.5 area = length * width
3.2 end_else
4. print area
Nested if Statements Problem-solving
-
8/3/2019 Week Selection C
60/110
Nested if Statements Problem-solvingexample
iii) C program
2-tier
nested if
#include main (){
float area, length, width;
printf (Enterlength and width\n);scanf (%f %f, &length, &width);
if (length == 0 || width == 0){
printf (WARNING- INPUT CANNOT BE ZERO);area = 0;
}else{
if (length < 0)length = -length; //find magnitude length
if (width < 0)width =-width; //find width magnitude
area = length * width}
printf (Area of a rectangle is %f\n);, area);}
-
8/3/2019 Week Selection C
61/110
Nested if Statements multiple tiers
Defense Ministry is to list names of malestaffs whose age is between 20-26 andnot yet married
if (gender == M)
if (marital_status == S)
if (age = 20)
printf (%s\n, name);
-
8/3/2019 Week Selection C
62/110
Notes on coding nested ifs
An else matches the nearest if thatdoes not have an else:
if (score < 100)
if (score > 90)
grade = 'A';
else ...// goes with second if,
// not first one
Proper indentation helps greatly
-
8/3/2019 Week Selection C
63/110
Exercise Week 7_7
Write nested if statements that perform
the following test:
If amount1 is greater than 10 andamount2 is less than 100, display the
greater of the two.
-
8/3/2019 Week Selection C
64/110
Logical Operators
4.10
-
8/3/2019 Week Selection C
65/110
Logical operators
Used to create relational expressions fromother relational expressions
Operators, meaning, and explanation:
&& AND New relational expression is true ifboth expressions are true
|| OR New relational expression is true if
either expression is true! NOT Reverses the value of an expressiontrue expression becomes false, andfalse becomes true
Using relational expressions for logical
-
8/3/2019 Week Selection C
66/110
Using relational expressions for logicalcomparison
Examples:
l i l i i l i l i
-
8/3/2019 Week Selection C
67/110
Relational operators pair in logical expressions
Revisited - Nested if Statements multiple
-
8/3/2019 Week Selection C
68/110
Revisited Nested if Statements multipletiers
The statement can also be written as:
if (gender == L) && (marital_status == S) && (age = 20)printf(%s\n, name);
L i l O
-
8/3/2019 Week Selection C
69/110
Logical Operators - notes
! has highest precedence, followed by &&,then ||
If the value of an expression can be
determined by evaluating just the sub-expression on left side of a logical operator,then the sub-expression on the right side willnot be evaluated (short circuit evaluation)
!(x > 2)
!x > 2
-
8/3/2019 Week Selection C
70/110
Checking Numeric Ranges withLogical Operators
4.11
Checking Numeric Ranges with Logical
-
8/3/2019 Week Selection C
71/110
g g gOperators
Used to test to see if a value falls inside arange:
if (grade >= 0 && grade
-
8/3/2019 Week Selection C
72/110
Validating User Input
4.12
V lid ti U I t
-
8/3/2019 Week Selection C
73/110
Validating User Input
Input validation: inspecting input data todetermine whether it is acceptable
Bad output will be produced from bad
input Can perform various tests:
Range
Reasonableness
Valid menu choice
Divide by zero
F P 7 12
-
8/3/2019 Week Selection C
74/110
From Program 7-12
//Get the numeric test score
printf ("Enter your numeric test score and I will\n");printf ("tell you the letter grade you earned: ");scanf ("%d", &testScore);
if (testScore < 0 || testScore > 100) //Input validation{
//An invalid score was enteredprintf ("%d is invalid score.\n", testScore);printf ("Run the program again and enter a value\n");
printf ("in the range of 0 to 100.\n");}else{
//Determine the letter gradeif (testScore < 60)grade = 'F';else if (testScore < 70)
grade = 'D';else if (testScore < 80)
grade = 'C';else if (testScore < 90)
grade = 'B';else if (testScore
-
8/3/2019 Week Selection C
75/110
More About Variable Definitionsand Scope
4.13
M Ab t V i bl D fi iti d S
-
8/3/2019 Week Selection C
76/110
More About Variable Definitions and Scope
Scope of a variable is the block in which itis defined, from the point of definition tothe end of the block
Usually defined at beginning of function
May be defined close to first use
Still More About Variable Definitions and
-
8/3/2019 Week Selection C
77/110
Scope
Variables defined inside { } have local
or block scope
When inside a block within another block,can define variables with the same nameas in the outer block.
When in inner block, outer definition is not
available
Not a good idea
-
8/3/2019 Week Selection C
78/110
Exercise Week 7_8
What will the following program display ifuser enter test1 40 and test2 30?
if (sum>60){
int bonus=10;
test1+=bonus; test2+=bonus;
int sum=test1+test2;printf ("Test 1 with bonus: %d \n",
test1);
printf ("Test 2 with bonus: %d \n",
test2);
printf ("Sum with bonus: %d \n",
sum);
}
printf ("Test 1 : %d \n", test1);
printf ("Test 2 : %d \n", test2);
printf ("Sum: %d \n", sum);
getch();
return 0;}
int main ()
{
int test1;
printf ("Enter Test 1 score: ");scanf ("%d", &test1);
int test2;
printf ("Enter Test 2 score: ");
scanf ("%d", &test2);
int sum=test1+test2;printf ("Sum: %d \n", sum);
(cont. next)
-
8/3/2019 Week Selection C
79/110
Comparing Strings
4.14
Comparing Strings
-
8/3/2019 Week Selection C
80/110
Comparing Strings
You cannot use relational operators withC-strings
Must use the strcmp function to compare
C-strings strcmp compares the ASCII codes of the
characters in the C-strings. Comparison is
character-by-character
Comparing Strings
-
8/3/2019 Week Selection C
81/110
Comparing Strings
The expressionstrcmp(str1, str2)
compares thestrings str1 and str2 It returns 0 if the strings are the same
It returns a negative number if str1 < str2
It returns a positive number if str1 > str2
Comparing strings example
-
8/3/2019 Week Selection C
82/110
Comparing strings - example
strcmp(Newyork,Newyork)
will return zero because 2 strings are equal.
strcmp(their,there)
will return a 9 which is the numeric difference betweenASCII i and ASCII r.
strcmp(The, the)
will return 32 which is the numeric difference betweenASCII T & ASCII t.
Comparing Strings example
-
8/3/2019 Week Selection C
83/110
Comparing Strings - example
//This program correctly tests two C-strings for equality
//with the strcmp fuction.#include #include #include
int main (){
const int SIZE = 40;char firstString[SIZE], secondString[SIZE];
//Get two stringsprintf ("Enter a string: ");gets(firstString);printf ("Enter another string: ");gets(secondString);
//Compare them with strcmpif (strcmp(firstString, secondString) == 0)
printf ("You entered the same string twice.\n");else
printf ("The strings are not the same.\n");getch();
return 0;}
Comparing Strings example
-
8/3/2019 Week Selection C
84/110
Comparing Strings - example
-
8/3/2019 Week Selection C
85/110
Exercise Week 7_9
Refer back to Lab 7, Exe. 4, Program 7.5 inpg. 63.
Change the program that you wrote in
Exercise Week 7_6 : Change variable choice to variableiceCream[20]
Instead of using menu, use gets so the usercan enter the flavor and use strcmp to if /elseif statement.
-
8/3/2019 Week Selection C
86/110
The Conditional Operator
4.15
The Conditional Operator
-
8/3/2019 Week Selection C
87/110
The Conditional Operator
Can use to create short if/else
statements
Format: expr ? expr : expr;x
-
8/3/2019 Week Selection C
88/110
The Conditional Operator
The value of a conditional expression is The value of the second expression if the first
expression is true
The value of the third expression if the firstexpression is false
Parentheses () may be needed in an
expression due to precedence ofconditional operator
The Conditional Operator
-
8/3/2019 Week Selection C
89/110
The Conditional Operator
Condition operator vs if/elsestatements
(x100)
a=0;
else
a=1;
printf(Your grade is );
printf((score
-
8/3/2019 Week Selection C
90/110
The Conditional Operator - example
#include
#include
int main(){
const double PAY_RATE = 50.0;double hours, charges;
printf ("How many hours were worked? ");scanf ("%lf", &hours);
hours = hours < 5 ? 5 : hours; //conditional operatorcharges = PAY_RATE * hours;
printf ("The charges are $%.2lf", charges);getch();
return 0;}
-
8/3/2019 Week Selection C
91/110
Exercise Week 7_10
Rewrite the followingif/else statements asconditional expressions
if (x>y)
z = 1;
elsez = 20;
if (hours> 40)
wages *= 1.5;
else
wages *= 1;
if (result >= 0)
printf("The result is +ve);
else
printf("The result is -ve);
Rewrite the followingconditional expressions asif/else statements
j = k > 90 ? 57 : 12;
total += count == 1 ? sales :count * sales;
printf (((num % 2) == 0) ?
"Even\n" : "Odd\n");
-
8/3/2019 Week Selection C
92/110
The switch Statement
4.16
The switch Statement
-
8/3/2019 Week Selection C
93/110
The switch Statement
Used to select among statements fromseveral alternatives
In some cases, can be used instead of
if/else if statements
switch statement format
-
8/3/2019 Week Selection C
94/110
switch statement format
switch (expression) //integer or char
{
case exp1: statement1;
case exp2: statement2;...
case expn: statementn;
default: statementn+1;}
Conversion from if/else if to switch
-
8/3/2019 Week Selection C
95/110
Conversion from if/else if to switch
switch statement requirements
-
8/3/2019 Week Selection C
96/110
switch statement requirements
1) expression must be an integer
variable or an expression that evaluates
to an integer value2) exp1 through expn must be constant
integer expressions or literals, and must
be unique in the switch statement3) default is optional but recommended
switch statement how it works
-
8/3/2019 Week Selection C
97/110
switch statement how it works
1) expression is evaluated
2) The value of expression is comparedagainst exp1 through expn.
3) If expression matches value expi, the
program branches to the statement followingexpi and continues to the end of the switch
4) If no matching value is found, the programbranches to the statement after default:
switch statement example I
-
8/3/2019 Week Selection C
98/110
switch statement example I
switch statement example II
-
8/3/2019 Week Selection C
99/110
s tc state e t e a p e II
switch statement example III
-
8/3/2019 Week Selection C
100/110
a e e e a p e III
break statement
-
8/3/2019 Week Selection C
101/110
Used to exit a switch statement
If it is left out, the program "falls through"the remaining statements in the switch
statement
break statement - example
-
8/3/2019 Week Selection C
102/110
p
Flowchart - switch
-
8/3/2019 Week Selection C
103/110
Flowchart switch example
-
8/3/2019 Week Selection C
104/110
p
Printing the description of a grade
Using switch with a menu
-
8/3/2019 Week Selection C
105/110
g
switch statement is a natural choice formenu-driven program:
display the menu
then, get the user's menu selection use user input as expression in switch
statement
use menu choices as expr in casestatements
E i W k 7 11
-
8/3/2019 Week Selection C
106/110
Exercise Week 7_11
Change Program 7.5 in pg. 63 to : Input 1=> Output :Muhammads favorite
Ismaels favorite
Input 3=> Output :Adibahs favorite Munirahsfavorite
Input 2 => Output :Ismaels favorite
Input 4 => Output :Munirahs favorite
Back to slide #54
-
8/3/2019 Week Selection C
107/110
Testing for File Open Errors
4.17
Testing for File Open Errors
-
8/3/2019 Week Selection C
108/110
g p
To ensure there is no error in opening a file Example: opening and reading a file stor12.dat
#include
main()
{FILE *failptr;
failptr = fopen(stor12.dat, r);
if (failptr == NULL)
{
printf(Error in opening the file.\n);
exit(-1); //Program ends)
}
return 0;
}
E i W k 7 12
-
8/3/2019 Week Selection C
109/110
Exercise Week 7_12
Refer to Lab 6, Exe.2. Program 6.3 in pg.58.
Modify the program to detect if the open
files operation failed.
-
8/3/2019 Week Selection C
110/110
Thank You
Q & A