Introduction To Loops
Introduction To Loops
FOR EMBEDDED C
By
Dr. H. Parveen Sultana
Professor/SCOPE,
VIT,Vellore 19/12/2023
TYPES OF LOOPING CONSTRUCTS
1. For Loop
2. While
3. Do-While
FOR LOOP SYNTAX
for (statement 1; statement 2; statement 3) {
// code block to be executed }
Statement 1 - executed one time before the execution of the code block.
int i;
}
Output : 0 1 2 3 4
FOR LOOP – TYPE1
int main() Note: return 0 is implicit at the
end of the programs, please
{
ignore that.
int lower_limit = 0;
int upper_limit = 100;
int count;
Initialization Termination Update
for(count = lower_limit; count < upper_limit; count ++) {
printf("%d, ",count); }
printf("\n");
}
Output
FOR LOOP- TYPE2
Initialization
Termination Update
Initialization
replaced
with a
semicolon
FOR LOOP - TYPE3
Note: Termination
statement cannot be
omitted from the for
loop.
Initialization
Termination
Initialization Omitted the
replaced with a update
semicolon statement
Update
FOR LOOP AND THE COMMA OPERATOR
Output
int main(){
int i, j;
Output:
the value of i and j : 0 10
the value of i and j : 1 9
WHILE LOOP SYNTAX
while (testExpression) {
// the body of the loop }
How while loop works?
• The while loop evaluates the testExpression inside the parentheses ().
• If testExpression is true, statements inside the body of while loop are
executed. Then, testExpression is evaluated again.
• The process goes on until testExpression is evaluated to false.
• If testExpression is false, the loop terminates.
EXAMPLE
int i = 0;
while (i < 5) {
printf("%3d", i);
i++;
}
output : 0 1 2 3 4
CONTD…
Notice the
similarity
Initialization
Termination
Update
PREDICT THE OUTPUT?
WHILE (1) OR WHILE (TRUE) & BREAK
STATEMENT
Run forever
If the condition is
satisfied break from
the while loop
Otherwise, print
count and update
DO- WHILE LOOP SYNTAX
do {
// code block to be executed
}while (condition);
How do...while loop works?
• The body of do...while loop is executed once. Only then, the condition
is evaluated.
• If condition is true, the body of the loop is executed again and
condition is evaluated once more.
• This process goes on until condition becomes false.
• If condition is false, the loop ends.
EXAMPLE
int i = 0;
do {
printf("%3d", i);
i++;
}
while (i < 5);
Output : 0 1 2 3 4
CONTD…
Output
CONTD…
Output
CONTD…
On which number
will this program give
an incorrect result ?
Output
CONTD…
Output
NESTED FOR LOOP
(0,0) (0,1) … … (0,4)
(1,0) : : : (1,4)
Matrix : : : : :
: : : : :
(4,0) … … … (4,4)
Output
CONTINUE STATEMENT
(a)
(a) (b)
Both (a) and (b) print odd numbers between 1 and 100. Note
that (a) has an implicit ‘continue’ when the condition is not
satisfied. (b) has an explicit ‘continue’ on the even numbers.
Output
PRACTICE PROBLEMS ON LOOPING
5. Reverse a number.
THANK YOU