CLang Lect08
CLang Lect08
1
do…while statement
do {
statements;
} while ( <condition> );
2
Example
• Calculate the sum of an integer #include <stdio.h>
array (ver 3) int main()
{
Algorithm: (version 3)
int aNum, sum = 0;
sum = 0
do
do
{
{
scanf("%d", &aNum) ;
input aNum
sum += aNum;
add aNum to sum
} while (aNum!=0);
} while (aNum!=0)
printf("Sum is %d\n", sum);
output sum
return 0;
}
3
Using do…while to verify input data
int n;
do {
printf(“Input a positive number: ”);
//n = -1;
fflush(stdin);
scanf(“%d”, &n)
if (n < 0)
printf(“Input data is not a positive
number\n”);
} while (n < 0);
4
Result
• Input a positive number: -2
• Input data is not a positive number
• Input a positive number: 5
• The number is 5
5
Infinitive loops
• Can create infinitive loops by while and for statements
• The loop is infinitive when the loop condition is always true
while (1)
{
...
}
for (;;)
{
...
}
6
Break statement
• Use break in an infinitive loop to terminate the loop
• Often use in infinitive loops
for (;;)
{
…
if (<condition>) break;
}
7
Example
#include <stdio.h>
int main()
{
int n;
while (1) {
printf("Input a positive number: ");
fflush(stdin);
scanf("%d", &n);
if (n<0){
printf("Must be positive. Try again\n");}
else
break;
}
printf("The number is %d\n", n);
return 0;
}
8
Result
Input a positive number: -2
Must be positive. Try again
Input a positive number: 5
The number is 5
9
Continue statement
• When a continue statement is encountered, a loop
will stop whatever it is doing and will go straight to
the start of the next loop pass.
for (…)
{
…
if (< condition >) continue;
…
}
10
Example
#include <stdio.h>
int main()
{
int n;
do {
printf("Input a positive number: ");
fflush(stdin);
scanf("%d", &n);
if (n < 0) {
printf("Bad number. Try again\n");
continue;
}
printf("The number is %d\n", n);
}
while (n<0);
return 0;
}
11
Result
Input a positive number: -2
Bad number. Try again
The number is 2
Input a positive number: 5
The number is 5
12
Exercises
(i) Write a program which prints out the prime factorization of
a number (treat 2 as the first prime). For example,
• on input 6, desired output is: 2 3
• " " 24, " " : 2223
• " " 23, " " : 23
13
Solution (exercise 1)
factor = 2;
do
{
if (n%factor==0) {
printf(“%5d”, factor);
n = n / factor;
} else {
factor++;
}
} while (n>1)
14
Solution (exercise 2)
first = n+1;
while(1) {
isPrime = 1;
for (factor = 2; factor<first; factor++)
if (first%factor==0) {
isPrime = 0;
break;
}
if (isPrime) {
printf(“The first greater prime is %d”, first);
break;
}
first++;
}
15
Thank you
for your
attentions!