0% found this document useful (0 votes)
9 views9 pages

Control Structures in Programming

The document provides an overview of control structures in computer programming, including sequence, selection, and looping structures. It explains how these structures control the flow of a program, allowing for sequential execution, decision-making based on conditions, and repetition of actions. Examples of one-way and two-way selections, as well as pre-test and post-test loops, are presented to illustrate their implementation in algorithms.
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)
9 views9 pages

Control Structures in Programming

The document provides an overview of control structures in computer programming, including sequence, selection, and looping structures. It explains how these structures control the flow of a program, allowing for sequential execution, decision-making based on conditions, and repetition of actions. Examples of one-way and two-way selections, as well as pre-test and post-test loops, are presented to illustrate their implementation in algorithms.
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

CSC121: INTRODUCTION TO PROBLEM SOLVING

MODULE 5
Control Structures
In computer programming, a control structure is a fundamental concept that
determines the order in which statements or instructions are executed in a program.
Control structures allow you to control the flow of your program, making it possible
to perform different actions based on conditions, repeat actions multiple times, and
create more complex logic.

There are three fundamental structures that are used for the algorithmic resolution of
problems:

Sequence control structure: This refers to the line-by-line execution by which


statements are executed sequentially, in the same order in which they appear in the
program. They might, for example, carry out a series of read or write operations,
arithmetic operations, or assignments to variables.

Step 1: Read amount,

Step 2: Read years,

Step 3: Read rate,

Step 4: Calculate the interest with formula; Interest =


Amount*Years*Rate / 100
1

Step 5: Print interest


Page

©CSC121: Introduction to Problem Solving


Selections control structure: The selection control structure, also known as the
conditional control structure, is a fundamental programming concept that allows a
program to make decisions and choose different paths of execution based on certain
conditions or criteria.

This section discusses one-way and two-way selections.

One-Way Selection

A bank wants to send a notice to a customer if her or his account balance falls below
the required minimum balance. That is, if the balance is below the required minimum,
the bank should send a notice to the customer; otherwise, it should do nothing.
Similarly, if the policyholder of an insurance policy is a non-smoker, the company
wants to apply a 10% discount to the policy premium. Both of these examples involve
one-way selection. In most programming languages, one-way selections are
incorporated using the if statement.

if (logical expression)
statement

The logical expression is also called a condition; it decides whether to execute the
statement that follows it. If logical expression is true, the statement executes. If it is
false, the statement does not execute and the computer goes on to the next statement in
the program. The statement following the logical expression is sometimes called the
action statement. (Note the indentation of the action statement. We have indented it
four spaces to the right of the if statement in the previous line.)

Figure below shows the flow of execution of the if statement (one-way selection).

The following is an example that shows how an if statement works.


2
Page

if (score >= 90)

©CSC121: Introduction to Problem Solving


grade = 'A';

In this code, if the logical expression, score >= 90, evaluates to true, the assignment
statement, grade = 'A';, executes. If score >= 90 evaluates to false, the assignment
statement, grade = 'A';, is skipped. For example, if the value of score is 95, the value
assigned to the variable grade is A.

Two-Way Selection
In the previous section, you learned how to implement one-way selections in a
program. There are many situations in which you must choose between two
alternatives.
For example, if a part-time employee works overtime, the paycheck is calculated
using the overtime payment formula; otherwise, the paycheck is calculated using the
regular formula. This is an example of two-way selection. To choose between two
alternatives—that is, to implement two-way selections—Many languages provide the
if...else statement.

if (logical expression)
statement1
else
statement2

The structure begins with the word if, followed by a logical expression contained
within parentheses, followed by a statement, followed by the word else, followed by a
second statement. Statements 1 and 2 can be any valid program statements. In a two-
way selection, if the value of the logical expression is true, then statement1 executes.
If the value of the logical expression is false, then statement2 executes.

Figure below shows the flow of execution of the if. . .else statement (two-way
selection).
3
Page

©CSC121: Introduction to Problem Solving


Consider the following statements:

if (hours > 40.0) //Line 1


wages = 40.0 * rate + 1.5 * rate * (hours - 40.0);
//Line 2
else //Line 3
wages = hours * rate; //Line 4

If the value of the variable hours is greater than 40.0, then the wages include overtime
payment. Suppose that hours is 50. The logical expression in the if statement in Line 1
evaluates to true, so the statement in Line 2 executes. On the other hand, if hours is
30, or any number less than or equal to 40, the logical expression in the if statement in
Line 1 evaluates to false. In this case, the program skips the statement in Line 2 and
executes the statement in Line 4—that is, the statement following the reserved word
else executes.

Looping/Repetition Structure: Sometimes it is necessary to repeat a set of


statements several times. One way to do this is to type the set of statements in the
program over and over. For example, if you want to repeat a set of statements 100
times, you type the set of statements 100 times in the program. However, this way of
repeating a set of statements is impractical, if not impossible. Fortunately, there is a
simpler approach. Most languages provide statements like while, do..while, do.. until
and for to handle repetition, or looping structures that allow you to repeat a set of
statements until certain conditions are met. These looping structures are divided into
the pre-test, post-test, and counted loops.

The Pre-Test Loop


Condition is tested PRIOR to the execution of the statement block
• If the condition is TRUE:
– Perform the statement block (perform one iteration)
– Go back to the condition (to check again)
• If the condition is FALSE:
– “exit” from the loop (do not perform any more
iteration)
• The loop may potentially not be executed:
– if condition fails on first test

The while loop is an example of the pre-test loop and has the general form:

while (logical expression)


4

statement
Page

©CSC121: Introduction to Problem Solving


The logical expression is called a loop condition or simply a condition. The statement
is called the body of the loop. Moreover, the statement can be either a simple or
compound statement. Also, note that the parentheses around the logical expression are
part of the syntax. The figure below shows the flow of execution of a pre-test (while)
loop.

The logical expression provides an entry condition. If it initially evaluates to true, the
statement executes. The loop condition—the logical expression—is then re-evaluated.
If it again evaluates to true, the statement executes again. The statement (body of the
loop) continues to execute until the logical expression is no longer true. A loop that
continues to execute endlessly is called an infinite loop. To avoid an infinite loop,
make sure that the loop’s body contains one or more statements that ensure that the
loop condition—the logical expression in the while statement—will eventually be
false.

Example:

Everyday, a weather station receives 15 temperatures


expressed in Fahrenheit. A program is to be written which
will accept each Fahrenheit temperature, convert it to
Celsius and display the converted temperature to the
screen. After 15 temperatures have been processed, the
words ‘All temperatures processed’ are to be displayed on
the screen. The formula for the conversion is given
below.

Celsius = (Fahrenheit – 32) x 5/9


5
Page

Write an algorithm for the above problem.

©CSC121: Introduction to Problem Solving


Solution:
START
Set temperature_count to zero
while (temperature_count < 15)
Prompt for f_temp
Get f_temp
Compute c_temp = (f_temp - 32)* 5/9
Display c_temp
Increment temperature_count
END while
Display „All temperatures processed‟ to the screen
END

The Post-Test Loop


The condition is tested at the END of each iteration of the loop
– At least one iteration will be performed
• If the condition evaluates to TRUE, another iteration will be executed
• If the condition is FALSE, exit from the loop
• Expressed by:
– DO … WHILE loops (for algorithms)
– DO … WHILE (For most languages e.g C, C++, and Java)
The figure below shows the flow of execution of a post-test (DO..WHILE) loop.

Counted loops
• Execute the statement block a pre-determined number of times
– Number of iterations known in advance
• A control variable keeps count of the number of repetitions
– No need to change this explicitly in code
• May use i, j & k as control variables (historical)
– meaningful names better
6
Page

• FOR counter=m to n (algorithms)

©CSC121: Introduction to Problem Solving


• FOR (counter=m; counter<=n; m++) (C, C++, Java)

Example:
Rewrite the Fahrenheit_Celsius_conversion algorithm to
use the counted loop.
START
FOR temperature_count = 1 to 15
Prompt operator for f_temp
Get f_temp
Compute c_temp = (f_temp - 32)* 5/9
Display c_temp
END FOR
Display „All temperatures processed‟ to the
screen
END

Exercise

• A person invests N1000.00 in a savings account


yielding 5 percent interest. Assuming that all
interest is left on deposit in the account, calculate
and print the amount of money in the account at the
end of each year for 10 years. Use the following
formula for determining these amounts:

a = p(1+r)n

p is the original amount invested (i.e., the


principal),
r is the annual interest rate,
n is the number of years and
a is the amount on deposit at the end of the
nth year

• Write an algorithm using any of the looping structure


for the program to calculate the amounts.

Algorithms for some problems

Write an algorithm for the following:

1. Write down an algorithm to find the largest data value


7

of a set of given data values.


Page

©CSC121: Introduction to Problem Solving


Algorithm largest of all data values:

Step 1: LARGE = 0

Step 2: read NUM

Step 3: While NUM > = 0 do

3.1 if NUM > LARGE

3.1.1 then

[Link] LARGE = NUM

3.2. read NUM

Step 4: Write “largest data value is”, LARGE

Step 5: end.

2. Write an algorithm which will test whether a given


integer value is prime or not.

Algorithm prime testing:

Step 1: M = 2

Step 2: read N

Step 3: MAX = SQRT (N)

Step 4: While M < = MAX do

4.1 if (M* (N/M) = N)

4.1.1 then

[Link] go to step 7

4.2. M = M + 1

Step 5: Write “number is prime”

Step 6: go to step 8

Step 7: Write “number is not a prime”

Step 8: end.
8
Page

©CSC121: Introduction to Problem Solving


3. Write algorithm to find the factorial of a given number N

Step 1: PROD = 1

Step 2: I = 0

Step 3: read N

Step 4: While I < N do

4.1 I = I + 1

4.2. PROD = PROD* I

Step 5: Write “Factorial of”, N, “is”, PROD

Step 6: end.

4. Write an algorithm to compute sum of given data values until negative value is
entered.

Algorithm Compute – Sum

Step 1: SUM = 0

Step 2: I = 0

Step 3: read NEWVALUE

Step 4: While NEWVALUE >= 0 do

4.1 SUM = SUM + NEWVALUE

4.2 I = I + 1

4.3 read NEWVALUE

Step 5: Write “Sum of”, I, “data value is, “SUM

Step 6: END
9
Page

©CSC121: Introduction to Problem Solving

You might also like