Professional Documents
Culture Documents
I Semester 2008-09
Lecture 6
Many computational problems which require performing similar or same tasks a number of times.
Examples :
Print a statement 100 times. Print all odd integers upto 1000. Print all prime integers upto 10000.
10
11
12
13
While Loop
} statement_B;
14
Observations : 1. ? 2. ??
15
16
Observations : 1. The condition must change during an iteration 2. The condition must be true for rst 10 iteration and then become false.
17
Idea : keep a counter 1. The condition must change during an iteration 2. The condition must be true for rst 10 iteration and then become false
18
Idea : keep a counter 1. The condition must change during an iteration 2. The condition must be true for rst 10 iteration and then become false
19
Idea : keep a counter 1. The condition must change during an iteration 2. The condition must be true for rst 10 iteration and then become false
20
II : For Loop
21
For Loop
stmt_A;
for ( {
stmt_1 ; condition
stmt_2 )
Body
}
stmt_B;
22
stmt_A;
for ( {
stmt_1
; condition ;
stmt_2 )
Body
}
stmt_B;
23
stmt_A;
for ( {
stmt_1 ; condition
stmt_2 )
Body
}
stmt_B;
24
stmt_A;
for ( {
stmt_1 ; condition
stmt_2 )
Body
}
stmt_B;
25
stmt_A;
for ( {
stmt_1 ; condition
stmt_2 )
Body
}
stmt_B;
26
stmt_A;
for ( {
stmt_1
; condition ;
stmt_2 )
Body
}
stmt_B;
27
stmt_A;
for ( {
stmt_1
; condition ;
stmt_2
Body
}
stmt_B;
28
stmt_A;
for ( {
stmt_1 ; condition
stmt_2 )
Body
}
stmt_B;
29
stmt_A;
for ( {
stmt_1 ; condition
stmt_2 )
Body
}
stmt_B;
30
stmt_A;
for ( {
stmt_1 ; condition
stmt_2 )
Body
}
stmt_B;
31
stmt_A;
for ( {
stmt_1
; condition ;
stmt_2 )
Body
}
stmt_B;
32
stmt_A;
for ( {
stmt_1
; condition ;
stmt_2
Body
}
stmt_B;
33
stmt_A;
for ( {
stmt_1 ; condition
stmt_2 )
Body
}
stmt_B;
34
stmt_A;
for ( {
stmt_2 )
stmt_1;
}
stmt_B; stmt_2;
}
stmt_B;
35
Homework
Write programs using for and while loop which can execute the following tasks : 1. For an arithmetic progression with rst term a and common difference d, print rst 10 terms. 2. For a geometric progression with rst term a and common ratio r, print rst 15 terms. a,d,r may be declared as variables of type int.
36