0% found this document useful (0 votes)
51 views6 pages

Chapter 2 Selection

The document discusses selection statements in C++. It introduces if, if-else, and nested if statements. It provides syntax and examples to check conditions and execute code blocks based on true or false evaluations. Flowcharts are included to illustrate control flow. Revision questions at the end assess understanding of selection statements and their applications to problems like checking for consecutive numbers or the roots of a quadratic equation.

Uploaded by

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

Chapter 2 Selection

The document discusses selection statements in C++. It introduces if, if-else, and nested if statements. It provides syntax and examples to check conditions and execute code blocks based on true or false evaluations. Flowcharts are included to illustrate control flow. Revision questions at the end assess understanding of selection statements and their applications to problems like checking for consecutive numbers or the roots of a quadratic equation.

Uploaded by

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

School of Computing and Informatics

BCS 120/BIT 121 – Introduction to Object-Oriented Programming I


Chapter 2 – Selection

1 Introduction
Before writing a program to solve a particular problem, we must have a thorough understanding of the
problem and a carefully planned solution approach.

1.1 Algorithms and Pseudocode


The solution to any computing problem involves executing a series of actions in a specific order. A procedure
for solving computer problems in terms of

• actions to be executed, and

• the order in which these actions are to be executed

is called an algorithm.
Pseudocode is an artificial and informal language that helps in development of algorithms.

2 Control structures
Normally, statements in a program are executed one after the other in the order in which they are written.
This is referred to as sequential execution.

There are control (selection and iteration) structures which help the programmer to specify that the next
statement to be executed may be other than the next one in the sequence. This is called transfer of
control.

2.1 Flowcharts
A flowchart is a graphical representation of an algorithm or of part of an algorithm. Flowcharts are drawn
using certain special-purpose symbols such as rectangles, diamonds, rounded rectangles and small circles.

A flowchart is a diagram that describes an algorithm or process, showing the steps as boxes of various
kinds, and their order by connecting these with arrows. Process operations are represented in these boxes,
and arrows connecting them represent the flow of control. A diamond box denotes a Boolean condition and
a rectangle box represents statements.
2.2 Selection statements in C++
C provides three selection statements:-

1. if selection statement (one-way if statement)

2. if...else selection statement (two-way if...else statement)

3. switch statement

2.3 if Selection statement


This selection statements checks a boolean condition (a condition that returns True or False) and execute
subsequent block of code if the condition is true or do nothing if the condition is false. A one-way if statement
executes an action if and only if the condition is true. The general syntax of if selection statement is
1 if (boolean−condition)
2 {
3 statment(s); //code to be executed if condition is True
4 }

For example, a piece of code that will check if a number is even and display the number if it is even will
look like
1 #include<iostream>
2 using namespace std;
3 int main()
4 {
5 int x;
6 cout <<”Enter a Number: ”; //prompt message to the user
7 cin >>x; //read a number from keyboard
8
9 //check if the number is even
10 if ( x % 2 == 0)
11 {
12 cout << x << ” is Even”; //dispaly the number if its even
13 }
14
15 return 0;
16 }

The general flowchart of an if statement is as shown in Figure 1 If the boolean-expression evaluates to true,

Figure 1: if flowchart

the statements in the block are executed. Consider a code fragment below
1 const float PI = 3.142;
2 int radius ;
3 cin >> radius;
4 if (radius >= 0) {
5 float area = radius ∗ radius ∗ PI;
6 cout << ”Area of circle of radius ” << radius << ” is ” << area;
7 }

This code calculates and displays area of a circle only and only if the radius is greater or equal to 0.

2.4 if...else statement


An if-else statement decides the execution path based on whether the condition is true or false. A one-way
if statement performs an action if the specified condition is true. If the condition is false, nothing is done.
But what if you want to take alternative actions when the condition is false? You can use a two-way if-else
statement. The actions that a two-way if-else statement specifies differ based on whether the condition is
true or false. Here is the syntax for a two-way if-else statement:
1 if (boolean−expression)
2 {
3 statement(s); //for−the−true−case;
4 }
5 else
6 {
7 statement(s); //for−the−false−case;
8 }

The flowchart of the statement is shown in Figure 2

Figure 2: An if-else statement executes statements for the true case if the Boolean-expression evaluates to
true; otherwise, statements for the false case are executed.

If the boolean-expression evaluates to true, the statement(s) for the true case are executed; otherwise,
the statement(s) for the false case are executed. For example, consider the following code:
1 const float PI = 3.142;
2 int radius ;
3 cin >> radius;
4 if (radius >= 0) {
5 float area = radius ∗ radius ∗ PI;
6 cout << ”The area for the circle of radius ” << radius <<” is ” << area;
7 }
8 else {
9 cout << ”Circle cannot have a negative radius”;
10 }
If radius >= 0 is true, area is computed and displayed; if it is false, the message ”Circle cannot have a
negative radius” is displayed.

Note 1. The braces can be omitted if there is only one statement within them. The braces enclosing the
printf(”Circle cannot have a negative radius”); statement can therefore be omitted in the preceding
example.

Here is another example of using the if-else statement. The example checks whether a number is even or
odd, as follows:
1 #include<iostream>
2 using namespace std;
3 int main()
4 {
5 int x;
6 cout << ”Enter a Number: ”; //prompt message to the user
7 cin >> x; //read a number from keyboard
8
9 //check if the number is even
10 if ( x % 2 == 0)
11 {
12 cout << x << ” is Even\n”; //dispaly the number if its even
13 }
14 else
15 {
16 cout << x << ” is Odd\n”;
17 }
18
19 return 0;
20 }

2.5 Nested if and Multi-way if-else statements


An if statement can be inside another if statement to form a nested if statement.

The statement in an if or if-else statement can be any legal C statement, including another if or if-else
statement. The inner if statement is said to be nested inside the outer if statement. The inner if statement
can contain another if statement; in fact, there is no limit to the depth of the nesting. For example, the
following is a nested if statement:
1 if ( i > k)
2 {
3 if ( j > k)
4 cout << ”i and j are greater than k”;
5 }
6 else
7 cout << ”i is less than or equal to k”;

The if (j > k) statement is nested inside the if (i > k) statement. The statement given in code segment
below, for instance, assigns a letter grade according to the score, with multiple alternatives.
1 char grade;
2 int score ;
3 scanf(”%d”, &score);
4 if ( score >= 90)
5 grade = ’A’;
6 else
7 if ( score >= 80)
8 grade = ’B’;
9 else
10 if ( score >= 70)
11 grade = ’C’;
12 else
13 if ( score >= 60)
14 grade = ’D’;
15 else
16 grade = ’F’;

The flowchart of this code could be

Figure 3: Flowchart grading code

A better structure of the same code would be


1 char grade;
2 int score ;
3 scanf(”%d”, &score);
4 if ( score >= 90)
5 grade = ’A’;
6 else if ( score >= 80)
7 grade = ’B’;
8 else if ( score >= 70)
9 grade = ’C’;
10 else if ( score >= 60)
11 grade = ’D’;
12 else
13 grade = ’F’;

2.6 Common errors


Forgetting necessary braces, ending an if statement in the wrong place, mistaking == for =, and dangling
else clauses are common errors in selection statements. Duplicated statements in if-else statements and
testing equality of double values are common pitfalls.

Revision Questions
1. With illustrations, differentiate between if and if...else statements

2. A leap year is divisible by 400 and not divisible by 100 or is divisible by 4. Write a program that will
read year from the keyboard and check if its a leap year or not
3. The two roots of a quadratic equation ax2 + bx + c = 0 can be obtained using the following formula:
√ √
−b + b2 − 4ac −b − b2 − 4ac
r1 = and r2 =
2a 2a
where b2 − 4ac is called the discriminant of the quadratic equation. If it is positive, the equation has
two real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots.

Write a program that prompts the user to enter values for a, b, and c and displays the result based
on the discriminant. If the discriminant is positive, display two roots. If the discriminant is 0, display
one root. Otherwise, display The equation has no real roots.

Note: You can use pow(x, 0.5) from math.h to perform x

4. Write a program that will check if three numbers entered by the user are consecutive (follow each
other). Consecutive numbers are numbers like 1, 3, 2; 4, 5, 6; 0, 2, 1 etc

You might also like