1. Lecture05(Control Structure PART-II)
June 27, 2010
Today's Outline
Looping statements in C
• for loop
• while loop
• do-while loop
Jump Statements in C
• continue
• break
• goto
Md. Mahbub Alam Structured Programming Language (CSE- 1
1121)
2. for loop
General Format:
for( initialization; condition; increment/decrement )
{
statements; //body of the loop
}
Init
false
Condition
true
Body of loop
Inc / Dec
Md. Mahbub Alam Structured Programming Language (CSE- 2
1121)
3. for loop (Cont.)
Example:
int sum = 0, count;
for(count = 1; count <= 5; count++)
sum = sum + count; //body of the loop
printf("%d", sum);
Md. Mahbub Alam Structured Programming Language (CSE- 3
1121)
4. while loop
General Format:
while( condition )
{ Condition
false
statements; //body of the loop
true
}
Body of loop
int sum = 0, count;
count = 1;
while( count <= 5)
{
sum = sum + count;
count++;
}
printf("%d", sum);
Md. Mahbub Alam Structured Programming Language (CSE- 4
1121)
5. do while loop
Format:
do
{
Body of loop
statements; //body of the loop
}while( condition );
true
Condition
int sum = 0, count;
false
count = 1;
do
{
sum = sum + count;
count ++;
}while( count <= 5);
printf("%d", sum);
Md. Mahbub Alam Structured Programming Language (CSE- 5
1121)
6. loop (cont.)
• Loop
– Group of instructions computer executes repeatedly while some
condition remains true
• Counter-controlled repetition
– Definite repetition:
– Known in advance how many times loop will execute
– Control variable used to count repetitions
• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not known in advance
– Sentinel value indicates "end of data"
Md. Mahbub Alam Structured Programming Language (CSE- 6
1121)
7. continue
Skips the remaining statements in the body of a while, for or do…while
statement and proceeds with the next iteration of the loop
– while and do…while
• Loop-continuation test is evaluated immediately after the continue
statement is executed
– for
• Increment/ decrement expression is executed first, then the loop-
continuation test is evaluated
int i, sum = 0;
for(i=0; ;i++)
{
if(i%2==1)
continue;
sum += i;
}
Md. Mahbub Alam Structured Programming Language (CSE- 7
1121)
8. break
• Causes immediate exit from a while, for, do…while or switch
statement.
• Program execution continues with the first statement after the control
structure.
• Common uses of the break statement
- Escape early from a loop
- Skip the remainder of a switch statement
int i, sum=0;
for(i=1; ; i++)
{
sum += i;
if(sum >= 10)
break;
}
Md. Mahbub Alam Structured Programming Language (CSE- 8
1121)