CHAPTER 8 - Repetition Structure
CHAPTER 8 - Repetition Structure
Repetition Structure
Outline
while
do-while
Loop Elements
Loop repetition condition
The condition that controls loop repetition
Loop control variable
The variable whose value controls loop
repetition
The loop control variable must be
Initialization
Testing
Updating
Syntax of for statement
Syntax: for (initialization expression;
loop repetition condition;
update expression)
statement
Example: /* Display N asterisks */
for (count_star = 0; count_star <N; count_star += 1)
printf(“*”);
/* forloop.c*/
/* Simple for example*/
#include <stdio.h>
int main()
{
int x;
return 0;
}
Output
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Iteration: 6
Iteration: 7
Iteration: 8
Iteration: 9
Iteration: 10
Operator
Increment and decrement operators
Operator Sample Explanation
expression
++ ++a Increment a by 1 then use the new value of a in
the expression in which a resides
++ a++ Use the current value of a in the expression in
which a reside, then increments a by 1
-- --b Decrement b by 1 then use the new value of b in
the expression in which b resides.
statement
Syntax of while statement
Syntax : while (loop repetition condition)
statement
Example : /* Display N asterisks. */
count_star = 0 ;
while (count_star < N) {
printf(“*”) ;
count_star = count_star + 1 ; }
/* while.c*/
/* Simple while example*/
#include <stdio.h>
int main()
{
int x = 1;
while(x<=10) {
printf (“Iteration: %d \n”, x);
x++;
}
return 0;
}
}
do-while Loop (1 of 2)
this loop structure is similar to the while
loop.
#include <stdio.h>
int main()
{
int x = 1;
do {
printf (“Iteration: %d \n”, x);
x++;
}
while ( x <= 10);
return 0;
}
Infinite Loop
infinite loops are loops that continue
forever.
infinite loops are useful at times to force a
program to continue running for an
extended length of time.
it is a quick way to force the instructions to
be repeated several times.
Example
for (; ;)
printf (“this will continue to print forever\n”);
while(1)
{
printf (“this will continue to print forever\n”);
}
do
{
printf (“this will continue to print forever\n”);
}while(1);
break Statement
when the compiler encounters break in a
loop, the computer terminates the loop
and program control resumes at
statements after the loop.
Using break
for (x=0;x<11;x++)
{
if (x==5)
break;
printf(“%d\n”,x);
}
Output?
continue Statement
the continue keyword is :
to bypass the remaining statements within the
loop; and
Output?
Loop Exercises
Create a C program that loops from 1 to
100 and display odd numbers only.
Create a C program that counts the
number of whitespaces in a string input
Create a C program that contains the
factorial of n which its value is keyed-in by
user