Вы находитесь на странице: 1из 23

01/24/2020

Control Structures that Allow Repetition

Types of Repeated Execution

• Loop: Group of instructions that are executed


repeatedly while some condition remains true.

How loops are controlled?

Counter Sentinel
Controlled Controlled
Condition
Controlled

Programming and Data Structure 32

1
01/24/2020

• Counter-controlled repetition
– Definite repetition – know how many times loop will execute.
– Control variable used to count repetitions.

• Condition-controlled repetition
– Loop executes as long as some specified condition is true.

• Sentinel-controlled repetition
– Indefinite repetition.
– Used when number of repetitions not known.
– Sentinel value indicates “end of data”.

Programming and Data Structure 33

Counter-controlled Repetition

• Counter-controlled repetition requires:


– name of a control variable (or loop counter).
– initial value of the control variable.
– condition that tests for the final value of the control
variable (i.e., whether looping should continue).
– increment (or decrement) by which the control
variable is modified each time through the loop.

Programming and Data Structure 34

2
01/24/2020

Counter Controlled Loop


Read 5 integers
and display the
value of their counter = 1, sum = 0
sum.
false
counter < 6
int counter=1, sum=0, n; true
input n
while (counter <6 ) {
scanf (“%d”, &n);
sum = sum + n; sum = sum + n
counter++;
} counter++
printf (\nSum is: %d, sum); output sum

35

int counter, sum=0, n;

for (counter=1; counter<6; counter++)


{
scanf (%d, &n);
sum = sum + n;
}
printf (\nSum is: %d, sum);

Programming and Data Structure 36

3
01/24/2020

while Statement

• The “while” statement is used to carry out looping


operations, in which a group of statements is executed
repeatedly, as long as some condition remains satisfied.

while (condition) while (condition)


statement_to_repeat; {
statement_1;
...
statement_N;
}

Programming and Data Structure 37

false
C Single-entry /
single-exit
true structure

statement(s)

Programming and Data Structure 38

4
01/24/2020

while :: Examples
int digit = 0; int weight=100;

while (digit <= 9) while (weight > 65)


printf (%d \n, digit++); {
printf (Go, exercise,);
printf (then come back. \n);
printf (Enter your weight:);
scanf (%d, &weight);
}

Programming and Data Structure 39

Example: Sum of N Natural Numbers


int main () {
int N, count, sum;
START scanf (%d, &N);
sum = 0;
READ N count = 1;
while (count <= N) {
SUM = 0
sum = sum + count;
COUNT = 1 count = count + 1;
}
printf (Sum=%d\n, sum);
SUM = SUM + COUNT return 0;
}
COUNT = COUNT + 1

NO IS YES
COUNT > N? OUTPUT SUM

STOP

Programming and Data Structure 40

5
01/24/2020

Example: Maximum of inputs


printf (Enter positive numbers, end with -1.0\n);
max = 0.0;
scanf(%f, &next);

while (next != -1.0) {


if (next > max)
max = next;
scanf(%f, &next);
}
printf (The maximum number is %f\n, max) ;

Example of Sentinel-controlled loop


Inputs: 10 5 100 25 68 -1

Programming and Data Structure 41

do-while Statement

• Similar to “while”, with the difference that the


check for continuation is made at the end of
each pass.
– In “while”, the check is made at the beginning.
• Loop body is executed at least once.

do do {
statement_to_repeat; statement-1;
while (condition ); statement-2;

statement-n;
} while (condition );

Programming and Data Structure 42

6
01/24/2020

statement(s)
Single-entry /
single-exit
structure
false
C

true

Programming and Data Structure 43

do-while :: Examples
int digit = 0;

do
printf (%d \n, digit++);
while (digit <= 9);

int weight;

do {
printf (Go, exercise, );
printf (then come back. \n);
printf (Enter your weight:);
scanf (%d, &weight);
} while (weight > 65 );

Programming and Data Structure 44

7
01/24/2020

for Statement

• The “for” statement is the most commonly used


looping structure in C.
• General syntax:

for (expression1; expression2; expression3)


statement-to-repeat;

for (expression1; expression2; expression3)


{
statement_1;
:
statement_N;
}
Programming and Data Structure 45

• How it works?
– “expression1” is used to initialize some variable (called
index) that controls the looping action.
– “expression2” represents a condition that must be true
for the loop to continue.
– “expression3” is used to alter the value of the index
initially assigned by “expression1”.

int digit; int digit;


for (digit=0; digit<=9;digit++) for (digit=9;digit>=0;digit--)
printf (%d \n, digit); printf (%d \n, digit);

Programming and Data Structure 46

8
01/24/2020

expression1

false Single-entry /
expression2
single-exit
structure
true

statement(s)

expression3

Programming and Data Structure 47

for :: Examples
int fact = 1, i, N; int sum = 0, N, i;

scanf (%d, &N); scanf (%d, &N);

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


fact = fact * i; sum = sum + i * i;
printf (%d \n, fact);
printf (%d \n, sum);
Compute factorial
Sum of squares of N
natural numbers

Programming and Data Structure 48

9
01/24/2020

2-D Figure
Print
***** #define ROWS 3
#define COLS 5
*****
....
***** for (row=1; row<=ROWS; row++) {
for (col=1; col<=COLS; col++) {
printf(*);
}
printf(\n);
}

Programming and Data Structure 49

Another 2-D Figure


Print
* #define ROWS 5
** ....
int row, col;
*** for (row=1; row<=ROWS; row++) {
**** for (col=1; col<=row; col++) {
***** printf(* );
}
printf(\n);
}

Programming and Data Structure 50

10
01/24/2020

• The comma operator


– We can give several statements separated by commas in
place of “expression1”, “expression2”, and “expression3”.

for (fact=1, i=1; i<=10; i++) expression1


fact = fact * i;
false
expression2
for (sum=0, i=1; i<=N, i++)
sum = sum + i*i; true

statement(s)

expression3

Programming and Data Structure 51

for :: Some Observations

• Arithmetic expressions
– Initialization, loop-continuation, and increment can
contain arithmetic expressions.
for (k=x; k <= 4*x*y; k += y/x)
• "Increment" may be negative (decrement)
for (digit=9; digit>=0; digit--)
• If loop continuation condition initially false:
– Body of for structure not performed.
– Control proceeds with statement after for structure.

Programming and Data Structure 52

11
01/24/2020

A common mistake (; at the end)


int fact = 1, i; int fact = 1, i;

for (i=1; i<=10; i++) for (i=1; i<=10; i++);


fact = fact * i; fact = fact * i;
printf (%d \n, fact); printf (%d \n, fact);

Loop body will execute only


once!

Programming and Data Structure 53

Specifying “Infinite Loop”

for (; ;)
while (1) {
{
statements
statements
}
}

do {
statements
} while (1);

Programming and Data Structure 54

12
01/24/2020

The “break” Statement Revisited

• Break out of the loop { }


– can use with
• while
• do while
• for
• switch
– does not work with
• if
• else

• Causes immediate exit from a while, do/while, for or switch


structure.
• Program execution continues with the first statement after
the structure.

Programming and Data Structure 55

An example with “break”


#include <stdio.h>
main()
{
int fact, i;

fact = 1; i = 1;

while (i<10) { /* break when fact >100 */


fact = fact * i;
if ( fact > 100 ) {
printf (Factorial of %d above 100, i);
break; /* break out of the loop */
}
i++;
}
}

Programming and Data Structure 56

13
01/24/2020

The “continue” Statement

• Skips the remaining statements in the body of a while, for


or do/while structure.
– Proceeds with the next iteration of the loop.
• while and do/while
– Loop-continuation test is evaluated immediately after
the continue statement is executed.
• for structure
– expression3 is evaluated, then expression2 is evaluated.

Programming and Data Structure 57

An example with “break” and “continue”


fact = 1; i = 1; /* a program to calculate 10! */
while (1) {
fact = fact * i;
i ++;
if (i<10)
continue; /* not done yet ! Go to loop and
perform next iteration*/
break;
}

Programming and Data Structure 58

14
01/24/2020

Some Examples

Example: SUM = 12 + 22 + 32 + N2
int main () {
START int N, count, sum;
scanf (%d, &N) ;
sum = 0;
READ N
count = 1;
while (count <= N) {
SUM = 0 sum = sum + countcount;
COUNT = 1 count = count + 1;
}
SUM = SUM + COUNT  COUNT printf (Sum = %d\n, sum) ;
return 0;
}
COUNT = COUNT + 1

NO IS YES
COUNT > N? OUTPUT SUM

STOP

Programming and Data Structure 60

15
01/24/2020

Example: Computing Factorial


int main () {
START int N, count, prod;
scanf (“%d”, &N) ;
prod = 1;
READ N
for (count=1;count <= N; count++) {
prod = prod*count;
PROD = 1 printf (Factorial = %d\n, prod) ;
COUNT = 1 return 0;
}
PROD = PROD * COUNT

COUNT = COUNT + 1

NO IS YES
COUNT > N? OUTPUT PROD

STOP

Programming and Data Structure 61

Example: Computing ex series up to N terms


START

READ X, N

ex = 1 + x/1! + x2/2! + x3/3! + …


TERM = 1
SUM = 0
COUNT = 1

SUM = SUM + TERM


TERM = TERM * X / COUNT

COUNT = COUNT + 1

NO IS YES
COUNT > N? OUTPUT SUM

STOP

Programming and Data Structure 62

16
01/24/2020

Example: Computing ex series up to 4 decimal places


START

READ X

TERM = 1
SUM = 0
COUNT = 1

SUM = SUM + TERM


TERM = TERM * X / COUNT

COUNT = COUNT + 1

NO IS YES
TERM < 0.0001? OUTPUT SUM

STOP

Programming and Data Structure 63

Example: Test if a number is prime or not

#include <stdio.h>
main()
{
int n, i=2;
scanf (”%d”, &n);
while (i < n) {
if (n % i == 0) {
printf (”%d is not a prime \n”, n);
exit;
}
i++;
}
printf (”%d is a prime \n”, n);
}

Programming and Data Structure 64

17
01/24/2020

More efficient??
#include <stdio.h>
#include <math.h>
main()
{
int n, i=3;
scanf (”%d”, &n);
while (i < sqrt(n)) {
if (n % i == 0) {
printf (”%d is not a prime \n”, n);
exit(0);
}
i = i + 2;
}
printf (”%d is a prime \n”, n);
}
Programming and Data Structure 65

Example: Find the sum of digits of a number

#include <stdio.h>
main()
{
int n, sum=0;
scanf (”%d”, &n);
while (n != 0) {
sum = sum + (n % 10);
n = n / 10;
}
printf (”The sum of digits of the number is %d \n”, sum);
}

Programming and Data Structure 66

18
01/24/2020

Example: Decimal to binary conversion

#include <stdio.h>
main()
{
int dec;
scanf (”%d”, &dec);
do
{
printf (”%2d”, (dec % 2));
dec = dec / 2;
} while (dec != 0);
printf (”\n”);
}

Programming and Data Structure 67

Example: Compute GCD of two numbers

#include <stdio.h> 12 ) 45 ( 3
main()
36
{
9 ) 12 ( 1
int A, B, temp;
9
scanf (”%d %d”, &A, &B);
3 ) 9 ( 3
if (A > B)
{temp = A; A = B; B = temp;} 9
while ((B % A) != 0) { 0
temp = B % A;
B = A; Initial: A=12, B=45
A = temp; Iteration 1: temp=9, B=12,A=9
Iteration 2: temp=3, B=9, A=3
}
printf (”The GCD is %d”, A); B % A = 0  GCD is 3
}
Programming and Data Structure 68

19
01/24/2020

Shortcuts in Assignments

• Additional assignment operators:


+ =, – =, * =, / =, % =

a += b is equivalent to a = a + b
a *= (b+10) is equivalent to a = a * (b + 10)
and so on.

Programming and Data Structure 69

More about scanf and printf

20
01/24/2020

Entering input data :: scanf function

• General syntax:
scanf (control string, arg1, arg2, …, argn);
– “control string refers to a string typically containing data types of
the arguments to be read in;
– the arguments arg1, arg2, … represent pointers to data items in
memory.
Example: scanf (%d %f %c, &a, &average, &type);
• The control string consists of individual groups of
characters, with one character group for each input data
item.
– ‘%’ sign, followed by a conversion character.

Programming and Data Structure 71

– Commonly used conversion characters:


c single character
d decimal integer
f floating-point number
s string terminated by null character
X hexadecimal integer
– We can also specify the maximum field-width of a
data item, by specifying a number indicating the field
width before the conversion character.
Example: scanf (%3d %5d, &a, &b);

Programming and Data Structure 72

21
01/24/2020

Writing output data :: printf function

• General syntax:
printf (control string, arg1, arg2, …, argn);
– “control string refers to a string containing formatting
information and data types of the arguments to be output;
– the arguments arg1, arg2, … represent the individual output
data items.
• The conversion characters are same as in scanf.
• Can specify the width of the data fields.
– %5d, %7.2f, etc.

Programming and Data Structure 73

• Examples:
printf (The average of %d and %d is %f, a, b, avg);
printf (Hello \nGood \nMorning \n);
printf (%3d %3d %5d, a, b, a*b+2);
printf (%7.2f %5.1f, x, y);

• Many more options are available:


– Read from the book.
– Practice them in the lab.
• String I/O:
– Will be covered later in the class.

Programming and Data Structure 74

22
01/24/2020

An example

#include <stdio.h>
main() 0 -17.778
{ 20 -6.667
int fahr; 40 4.444
60 15.556
for (fahr=0; fahr<=100; fahr+=20) 80 26.667
printf (%3d %6.3f\n”, 100 37.778
fahr, (5.0/9.0)*(fahr-32));
}

Programming and Data Structure 75

Print with leading zeros

#include <stdio.h>
main() 000 -17.778
{
020 -6.667
int fahr;
040 4.444
060 15.556
for (fahr=0; fahr<=100; fahr+=20)
printf (“%03d %6.3f\n”, 080 26.667
fahr, (5.0/9.0)*(fahr-32)); 100 37.778
}

Programming and Data Structure 76

23

Вам также может понравиться