Professional Documents
Culture Documents
Chapter 6
Chapter 6
Prepared By:
Mdm. Nik Maria Nik Mahamood
Reference:
Hanly, Koffman, C Problem Solving and Program Design in C, Sixth Edition, Pearson
International Edition. Refer chapter 5 (pg. 242 – pg. 301)
INSPIRING CREATIVE AND INNOVATIVE MINDS
REPETITION STRUCTURES AND LOOP STATEMENTS
C IMPLEMENTATION
KIND WHEN USED
STRUCTURES
while
Input of a list of data of any for
Sentinel-controlled loop
length ended by a special value. do..while
• Syntax:
initialization expression;
Example #1:
int x = 0;
while (x < 4) {
printf(“The value of x is %d”, x);
x = x + 1;
}
Questions:
a) Draw a flowchart for the program fragment above.
b) What output are displayed by the program fragment above?
c) Rewrite the program segment above, using for and do ..while
loop.
Example #2:
Pseudocode:
• Question Start
Write a program that sum = 0
computes and displays bil = 0
the sum of five values while (bil < 5)
entered by user.
begin_while
Display “Enter value:”
Read value
sum = sum + value
bil = bil + 1;
end_while
Stop
INSPIRING CREATIVE AND INNOVATIVE MINDS
6.3 COMPUTING A SUM AND A PRODUCT IN A LOOP
• Example:
int x;
for (x = 0; x < 4; x++) {
printf (“The value of x is %d”, x);
}
INSPIRING CREATIVE AND INNOVATIVE MINDS
6.4 THE FOR STATEMENT
• Example #1:
Counter-controlled Loop Based On The User Input
int sum = 0, bil = 0, noOfInput, value;
printf (“Enter number of input:”);
scanf (“%d”, &noOfInput);
Sentinel-Controlled Loops
• Example #2:
Sentinel-controlled Loop
Yes.
One repeatedly
Is there any 1. Sum the scores entered Program variable needed
repetition? 2. Get the next score Sentinel value (-99)
3. Checks to see whether
the score is - 99.
• Example:
int x = 0;
do {
printf (“The value of x is %d”, x);
x = x + 1;
} while (x < 4);