week8-loop
week8-loop
Loop
Topic of this week
• Loops
• The While,do Repetition Structure
• Notes and Observations
• Continue and break
• Programming Exercises
2
while, do Repetition Structure
• While Statement
• The expression is evaluated. If it is true, statement is
executed and expression is re-evaluated. This cycle
continues until expression becomes false.
while (expression) {
Statement1;
Statement2;
...
}
3
while, do Repetition Structure
• Example of While
#include <stdio.h>
#define PERIOD ‘.’
int main() {
char C;
while ((C = getchar())!= PERIOD)
putchar(C);
printf(“Good Bye.\n”);
}
Result?
4
while, do Repetition Structure
• Example:
int product = 2;
while ( product <= 1000 )
product = 2 * product;
true
product <= 1000 product = 2 * product
false
5
while, do Repetition Structure
• Do-While Statement
• The do-while, tests at the bottom after
making each pass through the loop body; the
body is always executed at least once
do {
statement1;
statement2;
…
} while (expression);
6
while, do Repetition Structure
• Example of Do-While
int i = 1, sum = 0;
do {
sum += i;
i++;
} while (i <= 50);
printf(“The sum of 1 to 50 is %d\n”, sum);
Result?
7
while, do Repetition Structure
counter = 1;
do {
printf( "%d ", counter );
} while (++counter <= 10);
true
condition
false
8
Continue and Break
9
Continue and Break
int c;
while ((c = getchar()) != -1) {
if (c == ‘.’)
break;
else if (c >= ‘0’ && c <= ‘9’)
continue;
else putchar(c);
}
printf(“*** Good Bye ***\n”);
10
Create Menu interaction
char ch;
do {
scanf(" %c", &c); //add a space before %c to remove
newline character
switch (ch) {
case 'A’:
/* do some thing */ break;
case 'B’:
/* do some thing */ break;
….
case 'Q’:
print Quit; break;
}
}while (ch!='Q');
11
input validation using do while
do {
printf("input n:");
scanf(&n);
if (n is not valid)
printf ("Warning\n");
}while (n is not valid);
12
Programming Menu
int choice;
do {
printf("Menu 1 2 3 4.. your selection:");
scanf("%d", &choice);
switch (choice){
case 1: do smt; break
case 2: do smt; break
case n: do smt; break
default: warning input not valid; break;
}
} while (choice != selection to quit);
13
Exercise 8.1
14
Exercise 8.2
16
Exercise 8.3
18
Exercise 8.4
20
Exercise 8.5
22
Exercise 8.6
24
Excercise 8.7
26
Exercise 8.8. SmallGame
27