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

Dr.

Khoa Dang Do

1
Lecture 4’s Overview
1. Loop Definition
2. Counting Loop - For Loop
3. Conditional Loop - While Loop and
Do...While Loop
4. Design a Program

2
1. Loop Definition

3
Repetition in Programming
 For most people, doing the same thing over and over again
is very boring

 Computers never get bored, so they’re great at doing


repetitive tasks

Why not let


the computer
do that for us ?

4
Definition of Loops
 Loop in programming is a mechanism
to repeat blocks of statements
multiple times until some conditions
are met

 There are two main kinds of loops:

 Those that repeat a certain number

of times—counting loops

 Those that repeat until a certain

thing happens— conditional loops


5
2. Counting Loop - For Loop

6
Introduction of For Loops
 Used to execute a block of statements a given number of
times
 The for loop operation is controlled by the contents of the
parentheses that follow the keyword for
 The action to repeat is the statement immediately
following the first line that contains the keyword for

for ( init; condition; increment )


{
statement(s);
}
7
A Simple Example
int count;
for(count = 1 ; count <= 10 ; ++count)
printf("\n%d", count);

8
Introduction of For Loops
 The first control expression is to initialize the
iteration variable
 The second control expression must be a
logical expression to check the iteration
condition.
 If the expression evaluates to true, the loop
continues, and if it’s false, the loop ends
 The third control expression, ++count in this
case, is to change the value of the iteration
variable.
9
Initialization of For Loops
 You could declare and initialize the variable count to 1
outside the loop
int count = 1;
for( ; count <= 10 ; ++count)
printf("\n%d", count);
printf("\nWe have finished.\n");
 You can also declare the loop variable within the first loop
control expression (count does not exist once the loop
ends)-For compliers with C99 mode only
for(int count =1; count <= 10 ; ++count)
printf("\n%d", count);
printf("\nWe have finished.\n");
10
Initialization of For Loops
 For Dev C++, to compile in C99 mode: In the project options, go
to 'parameters', then add '-std=c99' to the 'compiler' textbox

 When several variables are initialized, you can separate them by


commas

for(int i = 1, j = 2 ; i<=5 ; i++, j = j+2)


printf("\n %5d", i*j);

 The output produced by this fragment will be the values 2, 8, 18,


32, and 50 on separate lines

11
Conditions of For Loops
 The condition is a logical expression to determine whether
the loop should continue to be executed
for(int i = 1; i<=5 ; i++)
printf("\n %d", i);

for(int i = 1,j=10; i<j; i+=2, j++)


printf("\n %d", i);
 The condition is tested at the beginning of the loop rather
than at the end. If it is false, the for loop does not execute
any time at all.

12
Multiple Conditions in For
Loops
 Generally you can use '&&' or '||' to create multiple
conditions in a for loop

for(int i = 0,j=0; (i<10)&&(j<20); i++,j+=5)


printf("\n %d", i);

 Is this a valid way to create multiple conditions in For


Loop? (NO)
for(int i = 0,j=0; j<20,i<10; i++,j+=5)
printf("\n %d", i);

13
Increment of For Loops
 Be executed at the end of each loop iteration and is usually
(but again not necessarily) an increment or decrement of
one or more loop control variables
for(int i = 1; i<=5 ; i++)
printf("\n %d", i);
for(int i = 10; i>0; i--)
printf("\n %d", i);

 If several variables are modified, you separate the


expression by commas
for(int i = 0,j=0; (i<10)&&(j<20); i++,j+=5)
printf("\n %d", i); 14
The Increment Operator
 The increment operator takes the form ++, adds 1 to the
variable it acts on

 The following three statements all have exactly the same


effect
count = count + 1;
count += 1;
++count;

 You can also use the increment operator in an expression

int count = 5;
total = ++count + 6;//total=12
15
The Prefix and Postfix
Increment Operator
 The prefix operator ++ is written in front of the variable
while the postfix operator ++ is written after the variable

 The effect is significantly different between the prefix form


and postfix form when they are used in an expression

int count = 5;
total = ++count + 6;//total=12

int count = 5;
total = 6+ count++;//total=11

16
The Prefix and Postfix
Increment Operator
 If you write count++ in an expression, the incrementing of
the variable count occurs after its value has been used

 If you have an expression such as a+++ b, does it mean a++


+ b or a + ++ b? (The answer is a++ + b)

 It’s a good idea to use parentheses in all these cases to make


sure there’s no confusion

x = (a++) + b;
y = a + (++b);
17
The Decrement Operator
 The decrement operator takes the form --, subtracts 1 from
the variable it acts on

 The following three statements all have exactly the same


effect
count = count - 1;
count -= 1;
--count;

 You can also use the decrement operator in an expression

int count = 5;
total = --count + 6;//total=10
18
The Prefix and Postfix
Decrement Operator
 The prefix operator -- is written in front of the variable
while the postfix operator -- is written after the variable

 The effect is significantly different between the prefix form


and postfix form when they are used in an expression

int count = 5;
total = --count + 6;//total=10

int count = 5;
total = 6+ count--;//total=11

19
The Prefix and Postfix
Decrement Operator
 If you write count-- in an expression, the decrementing of
the variable count occurs after its value has been used

 If you have an expression such as a--- b, does it mean a-- -b


or a - -- b? (The answer is a-- - b)

 It’s a good idea to use parentheses in all these cases to make


sure there’s no confusion

x = (a--) - b;
y = a - (--b);
20
An Example: Summing
Numbers

21
An Example: Summing
Numbers

22
How It Works
 Declaring and initializing two variables that you’ll
need during the calculation

long sum = 0L; /* Stores the sum of the integers */


int count = 0; /* The number of integers to be
summed */

 The sum is calculated in the following loop:

for(int i = 1 ; i <= count ; i++)


sum += i;

23
The Flexible For Loop
 You can carry out a calculation within the third control
expression in a for loop
/* Sum integers from 1 to count */
for(int i = 1 ; i<= count ; sum += i++ );
 The loop statement is empty: it’s just the semicolon
after the closing parenthesis

 It works correctly because you’ve used the postfix form


of the increment operator (try with the prefix form ++)

24
The Flexible For Loop
 You could sum the first n integers backward if you wish

/* Sum integers from count to 1 */


for(int i = count ; i >= 1 ; sum += i--);

 The loop counter is initialized to count, rather than to


1, and it’s decremented on each iteration
 If you used the prefix form, the answer would be
wrong

25
A for Loop with No
Parameters
 The minimal for loop looks like this
for( ; ; )
statement;
 Statement could also be a block of statements
enclosed between br
 The loop will continue forever

 As a result, statement must contain the means of


exiting from the loop

26
The break Statement in a
Loop
 The break statement is introduced in the context of
the switch statement

 Its effect was to stop executing the code within the


switch block and continue with the first statement
following the switch

 The break statement works in essentially the same way


within the body of a loop—any kind of loop

27
An Example of Break
char answer = 0;
for( ;; )
{
/* Code to read and process some data */
printf("Do you want to enter some more(y/n): ");
scanf("%c", &answer);
if(tolower(answer) == 'n')
break; /* Go to statement after the loop */
}

28
Ex: A Minimal For Loop

29
Ex: A Minimal For Loop

30
The break Statement in a
Loop
 The break statement is introduced in the context of
the switch statement

 Its effect was to stop executing the code within the


switch block and continue with the first statement
following the switch

 The break statement works in essentially the same way


within the body of a loop—any kind of loop

31
How It Works
 Set up the loop to continue indefinitely because the for
loop has no end condition
for( ;; ) /* Indefinite loop */

 Display a prompt and read an input value in the loop


with these statements
/* Prompt for the next value */
printf("\nEnter a value: ");
/* Read the next value */
scanf(" %lf", &value);

32
How It Works
 Next add the value entered to your variable total:
total += value; /* Add value to total */

 You then increment the count of the number of values


++count; /* Increment count of values */

 You check with the user to see if more input is to be


entered
printf("Do you want to enter another value? (Y or N): ");
scanf(" %c", &answer);

33
How It Works
 The character entered is checked in the if statement:

if(tolower(answer) == 'n')
break; /* Exit from the loop */

 This statement calculates the average of the values and


display a result
printf("\nThe average is %.2lf\n", total/count);

34
More for Loop Control
Options
 You can increment or decrement the loop counter by
any amount that you wish

long sum = 0L;


for(int n = 1 ; n<20 ; n += 2)
sum += n;
printf("Sum is %ld", sum);

35
More for Loop Control
Options
 You aren’t limited to a single loop control expression
for(int n = 1 ; n<20 ; sum += n, n += 2);

 The third control expression consists of two


expressions separated by a comma

 These will execute in sequence at the end of each loop


iteration as
sum +=n;
n += 2
36
Floating-Point Loop
Control Variables
 The loop control variable can also be a floating-point
variable
double sum = 0.0;
for(double x = 1.0 ; x<11 ; x += 1.0)
sum += 1.0/x;

 It’s important to remember that it’s unwise to rely on


equality as the condition for ending a loop
for(double x = 0.0 ; x != 2.0 ; x+= 0.2)
printf("\nx = %.2lf",x);
37
Nested For Loops
 The for loop can be placed inside another for loop to
make a nested one

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


{

for (j = 0; j < 20; j++)
{

}

}

38
Ex:Nested For Loops

39
Ex:Nested For Loops

40
How It Works
 The inner loop completes all its iterations for each
iteration of the outer loop

 The outer loop starts off by initializing i to 1, and the


loop is repeated for successive values of i up to count

 For each iteration of the outer loop, for each value of i,


sum is initialized to 0, the inner loop is executed

sum = 0L; /* Initialize sum for the inner loop */

41
How It Works
 The inner loop accumulates the sum of all the integers
from 1 to the current value of i:
/* Calculate sum of integers from 1 to i */
for(int j = 1 ; j <= i ; j++)
sum += j;

 Each time the inner loop finishes, the printf() to


output the value of sum is executed

42
3. Conditional Loop - While
Loop and Do...While Loop

43
While Loop-Pretest Loop
 The mechanism for repeating a set of
statements
 It allows execution to continue for as
long as a specified logical expression
evaluates to true
while( expression )
Statement(s);
Next_Statement;
 Just like the for loop, the condition for
continuation of the while loop is tested
at the start
44
A Simple Example

45
Ex: Summing Numbers

46
Ex: Summing Numbers

47
How It Works
 Let’s discuss the while loop
while(i <= count)
sum += i++;

 When the loop starts, first check whether i <= count is


true

 The loop contains a single statement action that


accumulates the total in sum. What the statement
really means is this
sum += i;
i++;
48
How It Works
 The value of sum isn’t affected by the increment of i
until the next loop iteration
 Last time through the while loop: when i>count, you
leave the loop
 You can using ++ as a prefix operator like this:

sum += ++i;
 However, you need to start i off as 0 and change the
condition like this
int i = 0; while(i < count)
49
Nested While Loops
 The syntax for a nested while loop statement in C is
as follows

while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

50
Ex: Nested While Loops
/* Sums of integers with a while loop nested in a while loop */
#include <stdio.h>
int main(void) {
long sum = 0L; /* Stores the sum of integers */
int count = 0; /* Number of sums to be calculated */
int i=1,j;
/* Prompt for, and read the input count */
printf("\nEnter the number of integers you want to sum: ");
scanf(" %d", &count);
while (i<=count)
{
sum = 0L; /* Initialize sum for the inner loop */
/* Calculate sum of integers from 1 to i */
j=1;
while(j<=i)
sum += j++;
printf("\n%d\t%ld", i, sum); /* Output sum of 1 to i */
i++;
}
return 0;
} 51
Nesting a While Loop
within a For Loop
 You can nest a while loop inside a for loop

/* Sums of integers with a while loop nested in a for loop */


#include <stdio.h>
int main(void)
{
long sum = 0L; /* Stores the sum of integers */
int j = 1; /* Inner loop control variable */
int count = 0; /* Number of sums to be calculated */
/* Prompt for, and read the input count */
printf("\nEnter the number of integers you want to sum: ");

scanf(" %d", &count);


52
Nesting a While Loop
within a For Loop
for(int i = 1 ; i <= count ; i++){
sum = 0L; /* Initialize sum for the inner loop */
j=1; /* Initialize integer to be added */
printf("\n1");
/* Calculate sum of integers from 1 to i */
while(j <= i){
sum += j++;
printf("+%d", j); /* Output +j – on the same line */
}
printf(" = %ld\n", sum); /* Output = sum */
}
return 0;}
53
Nesting a While Loop
within a For Loop

54
Nested Loops and the goto
Statement
 You can nest one loop inside another, but it doesn’t
end there. You can nest as many loops one inside
another as you want
for(int i = 0 ; i<10 ; ++i)
for(int j = 0 ; j<20 ; ++k) /* Loop executed 10 times */
for(int k = 0 ; k<30 ; ++k) /* Loop executed 10x20 times */

{
/* Loop body executed 10x20x30 times */
/* Do something useful */
}
 Thus the body of the innermost loop will be executed
6,000 times
55
Nested Loops and the goto
Statement
 Occasionally, you’ll want to break out of all the nested
loops from the innermost loop and then continue with the
statement following the outermost loop

 A break statement in the innermost loop will only break


out of that loop, and execution will continue with the loop
controlled by j

 To escape the nested loops completely, it requires quite


complicated structures of break statements of each level

56
Nested Loops and the goto
Statement
 This is one situation in which the goto can be very
useful because it provides a way to avoid all the
complicated logic
for(int i = 0 ; i<10 ; ++i)
for(int j = 0 ; j<20 ; ++j) /* Loop executed 10 times */
for(int k = 0 ; k<30 ; ++k) /* Loop executed 10x20 times */
{ /* Loop body executed 10x20x30 times */
/* Do something useful */
if(getchar()==‘a’)
goto out;
}
out: /*Statement following the nested loops */ 57
The Do-While Loop
 The third type of loop is the do-while loop
do {
Statement(s);
}
while(expression);
 There’s actually a very subtle difference between the do-
while loop and the other two

 The test for whether the loop should continue is at the end
of the loop

 The loop statement or statement block always executes at


least once
58
The Do-While Loop
 Notice the semicolon after the while statement in a do-
while loop

 The loop will exit only when the value of expression


becomes false (zero)

59
The Do-While Loop

60
Ex: The Do-While Loop
/* Reversing the digits */
#include <stdio.h>
int main(void)
{
int number = 0; /* The number to be reversed */
int rebmun = 0; /* The reversed number */
int temp = 0; /* Working storage */
/* Get the value to be reversed */
printf("\nEnter a positive integer: ");
scanf(" %d", &number);
temp = number;
61
Ex: The Do-While Loop
/* Reverse the number stored in temp */
do
{
rebmun = 10*rebmun + temp % 10; /* Add the rightmost
digit */
temp = temp/10; /* Remove the rightmost digit */
} while(temp); /* Continue while temp>0 */
printf("\nThe number %d reversed is %d rebmun ehT\n",
number, rebmun );
return 0;
}
62
Ex: The Do-While Loop

63
How It Works
 Assume that the number 43 is entered by the user
 The program copies the value in number to the
variable temp:
temp = number; /* Copy to working storage */

 It is necessary as the process of reversing the digits


destroys the original value

64
How It Works
 The reversal of the digits is done in the do-while loop:
do
{
rebmun = 10*rebmun + temp % 10; /* Add the
rightmost digit */
temp = temp/10; /* Remove the rightmost digit */
} while(temp); /* Continue while temp>0 */

 The do-while loop is most appropriate here because


any number will have at least one digit
65
The continue Statement
 Sometimes a situation will arise in which you don’t
want to end a loop, but you want to skip the current
iteration and continue with the next

 The continue statement in the body of a loop does this


and is written simply as follows continue;

for(int day = 1; day<=7 ; ++day)


{
if(day == 3)
continue;
/* Do something useful with day */
}
66
4. Design a Program

67
The Problem- Simple
Simson
 Simple Simon is a memory-test game

 The computer displays a sequence of digits on the


screen for a short period of time

 You then have to memorize them, and when the digits


disappear from the screen, you must enter exactly the
same sequence of digits

 Each time you succeed, you can repeat the process to


get a longer list of digits
68
The Analysis
 The program must generate a sequence of integers
between 0 and 9 and display the sequence on the
screen for one second before erasing it

 The player then has to try to enter the identical


sequence of digits

 A score is then calculated based on the number of


successful tries and the time taken

69
The Analysis

70
The Solution-Step 1
 Start by putting in the main loop for a game.

 The player will always want to have at least one game,


so the loop check should go at the end of the loop.

 The do-while loop fits the bill very nicely.

#include <stdio.h> /* For input and output */


#include <ctype.h> /* For toupper() function */
int main(void)
{
/* Records if another game is to be played */
char another_game = 'Y';
/* Rest of the declarations for the program */
/* Describe how the game is played */

71
The Solution-Step 1
printf("\nTo play Simple Simon, ");
printf("watch the screen for a sequence of digits.");
printf("\nWatch carefully, as the digits are only
displayed"
" for a second! ");
printf("\nThe computer will remove them, and then
prompt you ");
printf("to enter the same sequence.");
printf("\nWhen you do, you must put spaces between the
digits. \n");
printf("\nGood Luck!\nPress Enter to play\n");
scanf("%c", &another_game); 72
The Solution-Step 1
/* One outer loop iteration is one game */
do
{
/* Code to play the game */
/* Output the score when the game is finished */
/* Check if a new game is required */
printf("\nDo you want to play again (y/n)? ");
scanf("%c", &another_game);
} while(toupper(another_game) == 'Y');
return 0;
}

73
The Solution-Step 2
 You can add a declaration for another variable, called
correct to record whether the entry from the player is
correct or not
#include <stdio.h> /* For input and output */
#include <ctype.h> /* For toupper() function */
#include <stdbool.h> /* For bool, true, false */

74
The Solution-Step 2
int main(void)
{
/* Records if another game is to be played */
char another_game = 'Y';
/* true if correct sequence entered, false otherwise */
bool correct = true;
/* Rest of the declarations for the program */

75
The Solution-Step 2
do
{
correct = true; /* By default indicates correct
sequence entered */
/* Other code to initialize the game */
/* Inner loop continues as long as sequences are
entered correctly */
while(correct)
{
/* Play the game */
}
/* Output the score when the game is finished */
76
The Solution-Step 3
 You have a slightly more difficult task to do: generating
the sequence of random digits

 There are two problems to be tackled here

 The first is to generate the sequence of random digits

 The second is to check the player’s input against the

computer-generated sequence

 The main difficulty with generating the sequence of


digits is that the numbers have to be random

77
The Solution-Step 3
 Let’s add some more codes

#include <stdio.h> /* For input and output */


#include <ctype.h> /* For toupper() function */
#include <stdbool.h> /* For bool, true, false */
#include <stdlib.h> /* For rand() and srand() */
#include <time.h> /* For time() function */

78
The Solution-Step 3
 Let’s add some more codes

bool correct = true;


/* Number of sequences entered successfully */
int counter = 0;
int sequence_length = 0; /* Number of digits in a
sequence */
time_t seed = 0; /* Seed value for random number
sequence */
int number = 0; /* Stores an input digit */
/* Rest of the declarations for the program */

79
The Solution-Step 3
 Let’s add some more codes

do
{
correct = true; /* By default indicates correct sequence
entered */
counter = 0; /* Initialize count of number of successful
tries */
sequence_length = 2; /* Initial length of a digit
sequence */
/* Other code to initialize the game */

80
The Solution-Step 3
 Let’s add some more codes
while(correct)
{
/* On every third successful try, increase the sequence
length */
sequence_length += counter++%3 == 0;
/* Set seed to be the number of seconds since Jan 1,1970
*/
seed = time(NULL);
/* Generate a sequence of numbers and display the number
*/
srand((unsigned int)seed); /* Initialize the random
sequence */
for(int i = 1; i <= sequence_length; i++)
printf("%d ", rand() % 10); /* Output a random digit */
/* Wait one second */
/* Now overwrite the digit sequence */
/* Prompt for the input sequence */ 81
The Solution-Step 3
 Let’s add some more codes
/* Check the input sequence of digits against the
original */
srand((unsigned int)seed); /* Restart the random
sequence */
for(int i = 1; i <= sequence_length; i++)
{
scanf("%d", &number); /* Read an input number */
if(number != rand() % 10) /* Compare against random
digit */
{
correct = false; /* Incorrect entry */
break; /* No need to check further... */
}
}
printf("%s\n", correct ? "Correct!" : "Wrong!");
}
/* Output the score when the game is finished */
82
The Solution-Step 4
 You must now erase the sequence, after a delay of one
second

 One way to get the program to wait is using library


function clock()

 The <time.h> header file defines a symbol


CLOCKS_PER_SEC that’s the number of clock ticks in
one second

83
The Solution-Step 4
 All you have to do is wait until the value returned by
the function clock() has increased by
CLOCKS_PER_SEC

for( ;clock() - now < CLOCKS_PER_SEC; ); /* Wait one


second */
 You also need to decide how you can erase the
sequence of computer-generated digits
 You can move to the beginning of the line by
outputting the escape character '\r', which is a carriage
return.
84
The Solution-Step 4
 All you then need to do is output a sufficient number
of spaces to overwrite the sequence of digits.

 Let’s add some codes

/* Stores current time - seed for random values */


time_t now = 0;
/* Rest of the declarations for the program */

85
The Solution-Step 4
 Let’s add some codes

/* One outer loop iteration is one game */


do
{
correct = true; /* By default indicates correct
sequence entered */
counter = 0; /* Initialize count of number of
successful tries */
sequence_length = 2; /* Initial length of a digit
sequence */
/* Other code to initialize the game */
86
The Solution-Step 4
 Let’s add some codes

/* Set seed to be the number of seconds since Jan


1,1970 */
seed = time(NULL);
now = clock(); /* record start time for sequence */

87
The Solution-Step 4
 Let’s add some codes
/* Wait one second */
for( ;clock() - now < CLOCKS_PER_SEC; );
/* Now overwrite the digit sequence */
printf("\r"); /* go to beginning of the line */
for(int i = 1; i <= sequence_length; i++)
printf(" "); /* Output two spaces */
if(counter == 1) /* Only output message for the first try
*/
printf("\nNow you enter the sequence - don't forget"
" the spaces\n");
else
printf("\r"); /* Back to the beginning of the line */
88
The Solution-Step 5
 All that remains is to generate a score to display, once
the player has gotten a sequence wrong

 You’ll use the number of sequences completed and the


number of seconds it took to complete them to
calculate this score

 It’s better to clear the keyboard buffer before going to


next round of the game

fflush(stdin); /* Flush the stdin buffer */

89
Output Display

90

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