Iterative Control Structure
Iterative Control Structure
Iteration/Loop
Loop is a sequence of instructions that is continually repeated until a certain condition is reached. It is used to
repeat execution of a block of code.
Execution of Loops
Execution of a loop is done inside a loop statement using a variable as a counter to keep track of which character is to be
checked. The counter variable may be incremented by one, each time through, so that the first element is examined the
first time through the loop, the second element the second time, and so forth.
Flowchart of a Loop
Types of Loops in C
1. Entry controlled loop
In an entry control loop in C, a condition is checked before executing the body of a loop. It is also called as a pre-
checking loop.
2. Exit controlled loop
In an exit controlled loop, a condition is checked after executing the body of a loop. It is also called as a post-checking
loop.
C Loop Constructs
The while loop
- The while loop is an entry control loop in C.
- In a while loop, a condition is evaluated before processing the body of the loop. If a
condition is true then and only then the body of a loop is executed.
Flowchart
Syntax:
while (condition) {
statement 1
statement 2
statement 3
...
statement n
}
Sample Problem 1: Implement using while
Make a C program that will print numbers from 1 to 10.
Output:
Practice 1:
Write C program that will ask the user to enter 10 integers and display the sum of all odd
integers.
Sample Outputs:
Test Case 1: Test Case 2:
The do-while loop
In a do…while loop, the condition is always executed after the body of a loop. It is also called
an exit-controlled loop.
Syntax:
do
{
statement/s;
} while(loop repetition condition);
Output:
Output:
Practice 2:
Make a C program to input an integer. Output all the factors of the number excluding itself.
Sample outputs:
Test Case 1:
Test Case 3:
Test Case 2:
Flowcharts of while and do while loops
Sample Program 5:
Make a C program that will print numbers from 1 to 10.
while loop implementation
Output:
Practice 3:
Write C program that will ask the user to enter 10 integers and display the sum of all odd
integers.
Sample Outputs:
Nested Loops in C
Syntax for nested for loop:
for (init; condition; increment) {
for (init; condition; increment) {
statement/s;
} //inner for loop
statement/s;
} //outer for loop
Outputs:
Note: You may use any loop you want.
Assignment 1: Assignment 3:
Make a C program that will display the Make a C program that will ask for the
factorial of a number. Note: Use a for loop. length and width of a rectangle and display
Definition: the perimeter. Ask the user to try again, if
n! (read as n factorial) the answer yes, enter the length and width. If
n! = n (n – 1)(n – 2) … (2) (1) the answer is no, the program terminates.
Example: Hint: use a do-while loop.
5! = 5(4)(3)(2)(1) = 120 Output:
0! = 1
-7! = invalid
Sample Outputs:
Assignment 4:
Make a C program to output the following
figure:
1
12
123
1234
12345
Hint: Use nested loop.