Topic 4
Topic 4
Looping
Regien D. Bacabis-Nakazato
Overview
• Parts of Looping
• The While Statement
• The Switch Statement
• The Do-While Statement
• The For Statement
• Nested Logic and loop
Control Structures
• Sequential
• Selection
• Repetition
Parts of Looping
• Initialization
• Test Expression
• Update Expression
• The Body of the loop
Parts of Looping
• Initialization
– Involves initializing loop variables
Parts of Looping
• Test Expression
– Decides whether the loop will be executed or not. This is
commonly a conditional statement/test expression.
Parts of Looping
• Update Expression
– Updates the values of loop variables after every iteration
of the loop
Parts of Looping
• The Body of the loop
– Contains the statement to be executed in the loop
The while statement
The while statement
Initialization
Test Expression
Update Expression
The while statement
The while statement
/* Calculation of simple interest for 3 sets of p, n and
r */
# include <stdio.h>
int main( )
{
int p, n, count ;
float r, si ;
count = 1 ;
while ( count <= 3 )
{
printf ( "\nEnter values of p, n and r " ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "Simple interest = Rs. %\nf", si ) ;
count = count + 1 ;
}
return 0;
}
Important Notes
• The statements within the while loop would keep getting executed till the
condition being tested remains true. When the condition becomes false, the
control passes to the first statement that follows the body of the while loop.
• In place of the condition there can be any other valid expression. So long as
the expression evaluates to a non-zero value the statements within the loop
would get executed.
• The condition being tested may use relational or logical operators as shown in
the following examples:
• The statements within the loop may be a single line or a block of statements.
In the first case, the braces are optional. For example,
Important Notes
• Almost always, the while must test a condition that will
eventually become false, otherwise you will encounter an
infinite loop
• Loop counter can also be decremented
• Loop counter can be of any countable data type
The ++ and -- operator
The operator ++ increments the value of i by
1, every time the statement i++ gets
executed.
While
The operator -- decrements the value of I by 1,
every time the statement i– is executed
Output:
The ++ and – operator precedence
Example:
Output:
Sample Problem
5 1
4 2
2 4
1 5
The do-while loop
The do-while loop
The do-while loop
VS
The do-while loop
Do while is used on situations wherein the exact number
of loops is not known beforehand.
Example:
Write a program that continually ask the user for a
number to be squared until the user stops.
The do-while loop
Example:
Write a program that continually ask the user for a number to be squared
until the user stops.
End of Lecture