Академический Документы
Профессиональный Документы
Культура Документы
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
4
Definition of Loops
Loop in programming is a mechanism
to repeat blocks of statements
multiple times until some conditions
are met
of times—counting loops
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
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
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);
12
Multiple Conditions in For
Loops
Generally you can use '&&' or '||' to create multiple
conditions in a for loop
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);
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
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
x = (a++) + b;
y = a + (++b);
17
The Decrement Operator
The decrement operator takes the form --, subtracts 1 from
the variable it acts on
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
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
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
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
24
The Flexible For Loop
You could sum the first n integers backward if you wish
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
26
The break Statement in a
Loop
The break statement is introduced in the context of
the switch statement
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
31
How It Works
Set up the loop to continue indefinitely because the for
loop has no end condition
for( ;; ) /* Indefinite loop */
32
How It Works
Next add the value entered to your variable total:
total += value; /* Add value to total */
33
How It Works
The character entered is checked in the if statement:
if(tolower(answer) == 'n')
break; /* Exit from the loop */
34
More for Loop Control
Options
You can increment or decrement the loop counter by
any amount that you wish
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);
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
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;
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++;
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
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
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
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 */
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 */
67
The Problem- Simple
Simson
Simple Simon is a memory-test game
69
The Analysis
70
The Solution-Step 1
Start by putting in the main loop for a game.
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
computer-generated sequence
77
The Solution-Step 3
Let’s add some more codes
78
The Solution-Step 3
Let’s add some more codes
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
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
85
The Solution-Step 4
Let’s add some codes
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
89
Output Display
90