Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Repetition in Programs
Iterative Statements in C
for
While
Do-while
for Statement
Structure: init
for (init; test-condn; incr/decr)
{
loop_body;
}
F
test
Executes loop body as long as test evaluates
to TRUE (non-zero). T
1. Initialization
2. Conditional Testing
loop_body
3. Updation of loop control variable
updation
Either 1 or 2 or 3 or ALL of them can be optional
/* 1+3+5+7+…….N terms */
for(count=1; count<=N; count++){
term = 2*count-1;
sum = sum + term;}
/* -1+2-3+4-5+6-……N terms */
for(count=1; count<=N; count++){
term = pow(-1,count)*count;
sum = sum + term;}
More Examples
i=1;
sum = 0;
for( ; ; )
sum + = i++;
How many times loop statement will be
executed?
for (i = 0,j = 7; i < j; i++, j--)
printf(“%d %d”,i,j);
Output???
for (i = 0,j = 7; i < j; i++, j--);
printf(“%d %d”,i,j);
Output???
Second Semester 2008-2009
6
Computer Programming TA C162
Nested Loops
The statement of for is again a for statement
Loop body can (of course) be another loop.
printf(“\n”);
}
Braces aren’t necessary,
but they make the code easier to read.
Second Semester 2008-2009
13
Computer Programming TA C162
Start
Initialize
Print primes
Stop
Second Semester 2008-2009
14
Computer Programming TA C162
F
Initialize num < 100
Print num T
if prime
Print num
num = num + 1
F
divisor <= 10
no F
divisors?
T
T Clear flag if
num%divisor == 0
Print num
divisor =
divisor + 1
While
while (test)
{ F
test
loop_body;
}
T
loop_body
scanf(“%d”,&num);
while(num!=-1){
sum = sum + num;
scanf(“%d”,&num);} /*sentinel control loop*/
Infinite Loops
The following loop will never terminate: Why???
x = 0;
while (x < 10)
printf(“%d ”, x);
for(;;){
loop body;}
Inference:
Loop body does not change condition, so test never fails.
This is a common programming error that can be difficult to find.
Note:
Either kind of loop can be expressed as the other, so it’s really a matter of
style and readability.
Do-While
do
{ loop_body
loop_body;
}while (test);
test
T
F
More Examples:
digit = 0;
while(digit <= 9)
printf(“%d\n”,digit++);
digit = 0;
do
printf(“%d\n”,digit++);
while(digit <= 9);
Loop Basics
1. Initialization of a condition variable.
2. Execution of the loop statements.
3. Test for a specified value of the condition variable.
4. Updating the condition variable.
Types of loops
• Counter controlled Loops
• Sentinel controlled Loops
• Input validation Loop
• General condition Loop