Professional Documents
Culture Documents
Computer Programming I: Spring 2015
Computer Programming I: Spring 2015
Computer Programming I
Hamid Harroud
School of Science and Engineering,
Al Akhawayn University in Ifrane
h.harroud@aui.ma
Spring 2015
Lecture 5
Repetition Statements:
while, for and do-while
Repetition in Programs
– while
– for
– do-while
Flow Diagram of Loop Choice
The while statement
• Example:
count_star = 0;
( 1900 <= year <= 2007 , 1 <= month <= 12, 1 <= day <= 31)
Nested Loops
• Consist of an outer loop with one or more
inner loops. (Fig. 5.13)
Nested Loop Example
• How many stars are displayed after the
following code fragment is executed:
*
**
***
****
*****
******
Example
• Write nests of loops that cause the
following output to be displayed:
0
01
012
0123
01234
0123
012
01
0
Flag-Controlled Loops
• fact (0) = 1
• fact (i) = i x (i-1) x (i -2) x … x 1
Example
• Write a program that reads in two integers
N1 and N2 and then display all odd
integers between N1 and N2.
(Assume N1 is always less than or equal to
N2).
Example
• Write an algorithm that calculates the
sum of the first N natural numbers for
any value of N.
Example
• Write a program that determines the
smallest, largest, and average values in
a collection of N numbers entered by
the user.
3N + 1 Problem
• Start with an integer n. If n is even, divide by 2. If
n is odd, multiply by 3 and add 1. Repeat this
process with the new value of n, terminating when
n = 1.
• For example, the following sequence of numbers
will be generated for n = 22:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1