Professional Documents
Culture Documents
Loops in C
Loops in C
Loops in C language
Asma Majeed
1
Introduction to Loops
Agenda
To be followed in today’s lecture
While
Do while
For
Nested Loops
Fundamentals of computer programming 2
loop or iteration
• In a program, the repetition structure directs the computer to repeat a
set of instructions until some conditions are met
• Once the condition is met, the repetition should stop
• Repetition is also referred to as loop or iteration
• Loops are used in programming to repeat a specific block until some
end condition is met. There are three loops in C programming:
• while loop (pre-test)
• For example, loops are used to count the number of words in a document, or
• to count the number of accounts that have past-due balances.
2. Sentinel-controlled repetition
is sometimes called indefinite repetition because it’s not known in advance
how many times the loop will be executed.
{
i = i * 2; /* loop body */
}
• When a while statement is executed, the controlling expression is
evaluated first.
• If its value is nonzero (true), the loop body is executed and the
expression is tested again.
• The process continues until the controlling expression eventually has the
value zero
Fundamentals of computer programming 7
Flowchart of while loop
1 1 2 3 5 8
• In general
• In C style
• We need some way of letting the program know that we have reached
the end of our list.
If (item==0)
break;
• continue starts re-executing the body of the loop from the top
• Lets modify the previous program to total only numbers larger than 0
• If the value of the expression is nonzero, the loop body is executed again
and then the expression is evaluated once more.
• All loops must have a test to continue, or they become infinite loops
// codes
}
expr1= initializationStatement;
expr2= testExpression;
expr3= updateStatement;
int num=10;
for (;num<20;num++)
Initialization part can be skipped from loop as shown below, the counter
variable is declared before the loop.
Note: Even though we can skip initialization part but semicolon (;) before condition is must, without which you will
get compilation error.
you can also skip the increment part as we did below. In this case semicolon (;) is must
after condition logic. In this case the increment or decrement part is done inside the
loop.
• Note: There can be mixed type of nested loop i.e. a for loop inside a while
loop, or a while loop inside a do-while loop.
Do we need a loop?
•Nested?
•How many iterations?
•Loop counter/condition variable?
printf("*");
printf(“\n”);