Omputer Rogramming: Session 3: Loops (Part 2)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

COMPUTER PROGRAMMING 1

Session 3: Loops (part 2)

Iván Amaya
CONTENTS
 SENTINEL VALUE

 EXERCISES

COMPUTER PROGRAMMING – SESSION 3 IVÁN MAURICIO AMAYA CONTRERAS 2


SENTINEL VALUE
A sentinel is used for detecting termination of data sets. This means that it
can be used within loops for creating more robust programs.

E.g.: Create a program that reads a set of grades and calculates the average
grade of the course. Consider the grade -1 as a sentinel value.

COMPUTER PROGRAMMING – SESSION 3 IVÁN MAURICIO AMAYA CONTRERAS 3


SENTINEL VALUE

What is wrong with


this algorithm?
What tests should be
carried out to identify
the problem?

COMPUTER PROGRAMMING – SESSION 3 IVÁN MAURICIO AMAYA CONTRERAS 4


EXERCISES
City growth

There are a couple cities (A and B). At the beginning of year 2000, city A
had popA inhabitants whilst city B had 50% more. If each city grows at a
rate ratA and ratB (respectively), create a program that simulates both
growths and report the year in which the population of A becomes higher
than the one of B.

COMPUTER PROGRAMMING – SESSION 3 IVÁN MAURICIO AMAYA CONTRERAS 5


EXERCISES
Student grades

A school offers a vast amount of courses and each one has a varied demand
of students. But, due to institutional policy, all classes are graded
throughout four exams. Thus, the board requires you to build an algorithm
for processing the grades of each student in a single course, calculating the
average grade of each student, as well as the number of students who failed
and the average grade achieved by the whole class.

Note: Student lists are ended by including a student with ID and grades
equal to zero. Also, average student grades should be printed with the ID.
COMPUTER PROGRAMMING – SESSION 3 IVÁN MAURICIO AMAYA CONTRERAS 6
EXERCISES
Number reversal

Given a number of four digits (read as a single variable), build an


algorithm that identify each digit and calculte the inverse number (i.e. the
same digits but in reverse order).

COMPUTER PROGRAMMING – SESSION 3 IVÁN MAURICIO AMAYA CONTRERAS 7


EXERCISES
Fibonacci series

The Fibonacci series is a recursive procedure, where the current number


corresponds to the sum of the two previous ones. Since the first two
elements of the series are zero and one, this means that the third element is
also one, followed by two, three, five, eight, and so on. Create an algorithm
that outputs the first n elements in the series.

COMPUTER PROGRAMMING – SESSION 3 IVÁN MAURICIO AMAYA CONTRERAS 8

You might also like