You are on page 1of 23

Chapter 3 Control Flow

3.4 Loops — While and For

3.4 Loops — While and For


 while statement:

while (expression)
statement

e.g.:
i = 1;sum = 0;
while (i <= 100) {
sum += i; /* sum=sum + i */
i++;
}
Chapter 3 Control Flow
3.4 Loops — While and For

 for statement: expr1;


for (expr1; expr2; expr3) while (expr2) {
statement statement
expr3;
}

sum = 0; i = 1;sum = 0;
for (i=1;i <= 100; i++) { while (i <= 100) {
sum += i; sum += i;
} i++;
}
Chapter 3 Control Flow
3.4 Loops — While and For
Example 1: input an integer n, and calculate n items’ sum :
1 1 1
1   
3 5 7  How to calculate n!
#include <stdio.h> (factorial) ? And how to
int main (void) output a table of 0!, 1!..n! ?
{
int denominator, flag, i, n;
double item, sum;
printf("Enter n:");
scanf("%d",&n);
flag=1, denominator=1, sum=0;
for (i=1; i<=n; i++){
item=flag*1.0/denominator;
sum = sum+item;
flag = -flag; denominator +=2;
}
printf("sum= %f\n", sum);
return 0;
}
Chapter 3 Control Flow
3.4 Loops — While and For

double fac(int m)
#include <stdio.h> {
double fac(int i); int i;
int main (void) double factorial=1;
{ for (i=1; i<=m; i++)
int i, n; factorial=factorial*i;
double factorial; return factorial;
printf("Enter n:"); }
scanf("%d",&n);
for (i=0; i<=n; i++){
factorial=fac(i);
printf("%d!= %.0f\n", i,factorial);
}
return 0;
}
Chapter 3 Control Flow
3.4 Loops — While and For

Example 2: Output an integer in its inverse order.

#include <stdio.h>
int main(void)
{
int integer;
printf("Enter a integer:");
scanf("%d", &integer);
while(integer > 0){
printf("%d", integer%10);
integer /= 10;
}
printf("\n");
return 0;
}
Chapter 3 Control Flow
3.4 Loops — While and For

Example 3: Convert a string to an integer


#include <ctype.h>
/* atoi: convert s to integer; version 2 */
int atoi(char s[])
{
int i, n, sign;
for (i = 0; isspace(s[i]); i++)
; /*skip white space*/
sign = (s[i] == ‘-’) ? -1 : 1;
if (s[i] == ‘+’ || s[i] == ‘-’)
i++; /* skip sign */
for (n = 0; isdigit(s[i]); i++)
n = 10 * n + (s[i] - ‘0’);
return sign * n;
}
Chapter 3 Control Flow
3.4 Loops — While and For

Example 4: Insert Sort.


void InsertionSort ( int V[ ], int N )
{
int i, j;
int tmp;

for ( i = 1; i < N; i++ ) {


Tmp = V[ i ]; /* the next coming card */
for ( j = i; j > 0 && V[ j - 1 ] > Tmp; j-- )
V[ j ] = V[ j - 1 ];
/* shift sorted cards to provide a position
for the new coming card */
V[ j ] = Tmp; /* place the new card at the proper position */
} /* end for-P-loop */
}

2/14
Chapter 3 Control Flow

〖 Example 〗 Input list 34, 8, 64, 51, 32,


3.4 Loops — While and For

21
(i=1) 34, 8, 64, 51, 32, 21
8, 34, 64, 51, 32, 21 (m→1)
(i=2) 8, 34, 64, 51, 32, 21
8, 34, 64, 51, 32, 21 (m→0)
(i=3) 8, 34, 64, 51, 32, 21
8, 34, 51, 64, 32, 21 (m→1)
(i=4) 8, 34, 51, 64, 32, 21
8, 32, 34, 51, 64, 21 (m→3)
(i=5) 8, 32, 34, 51, 64, 21
8, 21, 32, 34, 51, 64 (m→4)

Swapping two adjacent elements that are


out of place removes exactly one inversion.

There are 9 swaps needed to sort this list by insertion sort.


Chapter 3 Control Flow
3.4 Loops — While and For

Example 5: Shell Sort.

〖 Example 〗 Sort
: 81 94 11 96 12 35 17 95 28 58 41 75 15

5-sort 35 17 11 28 12 41 75 15 96 58 81 94 95

3-sort 28 12 11 35 15 41 58 17 94 75 81 96 95

1-sort 11 12 15 17 28 35 41 58 75 81 94 95 96
Chapter 3 Control Flow
3.4 Loops — While and For

/* shellsort: sort v[0]...v[n-1] into increasing order */


void shellsort(int v[], int n)
{
int gap, i, j, temp;
for (gap = n/2; gap > 0; gap /= 2)
for (i = gap; i < n; i++){
temp=v[i];
for (j=i; j >= gap; j- = gap)
if(temp<v[j-gap])
v[j]=v[j-gap];
else
break;
v[j] = temp;
}
}
Chapter 3 Control Flow
3.4 Loops — While and For

Example 6: Swap Sort.

void SwapSort(int v[], int n)


{
int i, j, temp;
for (i=1; i<n; i++)
for (j=i-1; j>=0&&v[j]>v[j+1]; j--){
temp = v[j];
v[j] = v[j+1];
v[j+1] = temp;
}
}
Chapter 3 Control Flow
3.4 Loops — While and For

Example 7: A building site needs 45 persons to convey 45


pieces of brick. Suppose each men, women, and two
children can convey tree, two, and one piece respectively,
how many conveying ways are there?
#include <stdio.h>
int main(void)
{
int men, women, child;
for(men=0; men<=45; men++)
for(women=0; women<=45; women++)
for(child=0; child<=45; child++)
if(men+women+child==45 &&
men*3+women*2+child*0.5==45)
printf("men=%d, women=%d, child=%d\n",
men, women, child);

return 0;
}
Chapter 3 Control Flow
3.4 Loops — While and For

Example 7: version2

#include <stdio.h>
int main(void)
{
int men, women, child;
for(men=0; men<=15; men++)
for(women=0; women<=22; women++){
child=45-men-women;
if(men*3+women*2+child*0.5==45)
printf("men=%d, women=%d, child=%d\
n",
men, women, child);
}
return 0;
}
Chapter 3 Control Flow
3.5 Loops — Do-While

3.5 Loops — Do-While


Syntax:
do
statement
while (expression);

Example:
sum=0;
i = 1;
do {
sum += i;
i++;
} while (i <= 100);
Chapter 3 Control Flow
3.5 Loops — Do-While

Example 1: Convert an integer to a string.


void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /*generate digits in reverse order*/
s[i++] = n%10+'0'; /*get next digit*/
} while ((n /= 10) > 0); /* delete it */
if (sign < 0) s[i++] = '-';
s[i] = '\0';
reverse(s);

}
Chapter 3 Control Flow
3.5 Loops — Do-While

Example 2: Reverse a string in place.

/* reverse: reverse string s in place */


void reverse(char s[])
{
int c, i, j;
for (i=0, j=strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
Chapter 3 Control Flow
3.5 Loops — Do-While

Example 3: Count the digits of an integer.

#include <stdio.h>
int digits(int);
int main(void)
{
int number;
printf("Enter a number:");
scanf("%d", &number);
int digits(int integer)
printf("It contains
{ %d digits.\n", digits(number));
return 0; int count=0;
} if(integer<0) integer=-integer;
do{
integer/=10;
count++;
} while(integer != 0);
return count;
}
Chapter 3 Control Flow
3.6 Break and Continue

3.6 Break and Continue


 Break statement :
e.g.1:  Break can only be
for (r = 1; r <= 10; i++) { applied to the Loop
area = PI * r * r; statement and switch
if (area > 100) break;
printf("%f\n", area); statement. 
}
e.g.2: remove trailing blanks, tabs, newlines
int trim(char s[])
{
int n;
for(n=strlen(s)-1; n>=0; n--)
if(s[n] != ‘ ‘ && s[n] != ‘\t’ && s[n] != ‘\n’)
break;
s[n+1]=‘\0’;
return n;
}
Chapter 3 Control Flow
3.5 Loops — Do-While

Example : Determine a prime.


#include <stdio.h>
int main(void)
{
int i, number;
printf("Enter a number:");
scanf("%d", &number);
for(i=2; i<=number/2; i++)
if(number % i == 0)
break;
if(i>number/2)
printf("%d is a prime number!\n", number);
else
printf("No! \n");
return 0;
}
Chapter 3 Control Flow
3.5 Loops — Do-While

Example : Print all the primes less than 100 .


#include <stdio.h>
#include <math.h>
int prime(int number);
int main(void)
{
int i, count=0;
for(i=2; i<=100;i++){ int prime(int number)
if( prime(i) == 1) { {
printf("%6d ",i); int i,n;
count++; n=sqrt(number);
if(count%10 == 0) for(i=2; i<=n; i++)
printf("\n"); if(number%i == 0)
} break;
} if(i>n)
printf("\n"); return 1;
return 0; else
} return 0;
}
Chapter 3 Control Flow
3.6 Break and Continue

 continue statement :
 what is the
It causes the next iteration of the enclosing for,
difference between
while, or do loop to begin.
break and continue?
e.g.:
for ( i = 0; i < n; i ++) { for (n = 100; n <= 200; n++) {
if( a[i] < 0 ) /* skip negative
if (n%3 == elements
0) */
continue; continue;
… /* do positive elements printf("%d
*/ ", n);
}
}
 In the while and do, the test part is executed
immediately; in the for, control passes to the increment
step. The continue statement applies only to loops, not to
switch.
Chapter 3 Control Flow
3.7 Goto and Labels

3.7 Goto and Labels


 Syntax:
goto label;
e.g.: determining whether arrays a and b have an
element in common
for(i = 0; i < n; i++)
for(j = 0; j < m; j ++)
if(a[i] == b[j])
goto found;
/* didn’t find any common element */
….
found:
/* got one: a[i]==b[j] */

Exercises

P.60 3-2

You might also like