COMPUTER PROGRAMMING 1
Session 2: Loops
Iván Amaya
CONTENTS
WHILE
DO-WHILE
FOR
EXAMPLES
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 2
WHILE LOOP
Ask first, shoot later
Cond
Process
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 3
DO-WHILE LOOP
Shoot first, ask later
Process
Cond
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 4
FOR LOOP
Shoot N bullets
cont = st, end
Process
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 5
EXAMPLES
Printing numbers
Create a program that prints the numbers from 0 to 10. Use different loop
structures
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 6
EXAMPLES
Printing numbers
While loop Do-While loop For loop
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 7
EXAMPLES
Counting numbers
Create a program that divides a given even number into two, until the
number becomes one. Print each number and the total amount of divisions.
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 8
EXAMPLES
Counting numbers
What happens when
num < 1?
While loop Do-While loop
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 9
EXAMPLES
Counting numbers
What happens when
num < 1?
What happens if there
is no data for
calculating div?
For loop
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 10
EXAMPLES
You are thinking on opening an account at a bank. There are several
options available and, thus, you would like to have a means of quickly
assessing which one is the best option for you. Specifically, you would like
to know how many months would it take to double an initial investment C,
at a given interest rate. Create a program to sort this problem out, reporting
the value after each month has passed.
After each bounce, a ball losses part of its energy. Assuming an initial
height (H), create a program that simulates each bounce, reporting the
number of bounces until the ball is unable to reach a height equal to one
fifth of the initial value.
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 11
EXAMPLES
You are developing an algorithm for data analysis. Said analysis requires
you to identify the amount of odd and even numbers in the data set.
Knowing that each data set contains a hundred data points, lay out the
algorithm for carrying out the required analysis.
Note: residue operations in CFD are given by the % operator
COMPUTER PROGRAMMING – SESSION 2 IVÁN MAURICIO AMAYA CONTRERAS 12