05 Selection
05 Selection
Department of Computer
Science
Exercise 5.1
• Write a C++ program to read an examination mark
from keyboard and print “pass” if mark >= 40.
C++ Selection (if Statement)
• One-Way (if) Selection
Syntax
if (expression)
{
statement(s)
}
• Example
Exercise 5.1
Write a C++ program
to print the biggest
number of the two
given numbers
Exercise 5.2
Write a C++ program
to print the biggest
number of the three
given numbers
Exercise 5.3
• Write a C++ program to print the grade for a given
mark.
0 40 60 75 100
Solution 1
Nested if and if...else Statements
• Nesting: one control statement in another
• Syntax of nested if...else statements:
if (condition1)
statement1;
else if (condition2)
statement2;
...
else if (condition-n)
statement-n;
else statement-z;
Exercise 5.4
Write a C++ program
to print the grade for a
given marks
Debug
Debugging is a methodical process of finding and
reducing the number of bugs, or defects
Debug
• Programming errors are called bugs
• Programming errors may be
– Compiler errors
– Runtime errors
– Logical errors
• Going through the code, examining it and looking for
something wrong in the implementation (bugs) and
correcting them is called debugging
Debugging Options
• Make break points
– Right click on statement and add break point
• Debug Commands
– F8 – Start / Continue
– F7 – Next Line
– Shift+F8 Stop
Exercise 5.5
• Write a C++ program that reads month as an integer
and print the name of the month
• Draw a flowchart to describe your solution
• Debug your code and find execution path for the
following
– Month = 1;
– Month = 12;
– Month = 6;
Switch
Run with number of possible execution paths
A switch works with the byte, short, char, and
int
primitive data types
Switch
• switch structure: alternate to if...else
• Example 1:
switch(x) {
case x1: statements1;
break;