iterative/loop/repetition statements revision
TRANSCRIPT
Iterative/Loop/Repetition Statements Revision
Week 02-part1
CC213:Programming Applications
2
• Repetition in Programs –why?
• Counting Loops – Using while statement • Compoundassignment operators
– Using for statement • Increment and Decrement Operators
• Conditional Loops – – – –
sentinel-Controlled loops Nested loop Do-While loop Flag-Controlled loop
Overview
3
• We have learned how to write code that chooses between multiple alternatives.
• It is also useful to be able to write code that repeats an action. Usually these actions either drawing or computations.
• Determine whether loops will be required in the general algorithm and if so which loop structure to choose from.
Repetition in Programs
Flow Diagram of Loop Choice Process
4
5
Two Types of Loops
count controlled loops
repeat a specified number of times
event-controlled loops
some condition within the loop body
changes and this causes the repetetion to
stop
6
while Statement
SYNTAX
while ( Expression )
{ .
. /*loop body */
.
}
NOTE: Loop body can be a single
statement, a null statement, or a block.
• This slide shows a program fragment that computes and displays the gross pay for seven employees. The loop body is the compound statements (those between { and }). • The loop repetition condition controls the while loop. count_emp = 0;
while (count_emp < 7) {
loop repetition condition
printf("Hours> "); scanf("%d",&hours);
printf("Rate> "); scanf("%lf",&rate);
pay = hours * rate;
printf("Pay is $%6.2f\n", pay);
count_emp = count_emp + 1;
}
printf("\nAll employees processed\n"); 6
while Statement Example
8
Every while loop will always contain three main
elements:
Priming: initialize your variables.
Testing: test against some known condition.
Updating: update the variable that is tested.
Parts of a While Loop
• If any of these are skipped it may produce an infinite loop
7
• Parts of the while Statement in previous example: – Initialization. i.e. count_emp = 0;
– Testing. i.e. count_emp < 7
– Updating i.e. count_emp = count_emp + 1;
Parts of a While Loop
• In the previous example we had count_emp < 7, but we may have more or less than 7 employees.
• To make our program fragment more general we should use a printf/scanf to get the number of employees and store it is num_emp.
• Now we can have count_emp < num_emp and our code is more general.
10
int count ;
count = 4; /* initialize loop variable */
while (count > 0) /* test expression */
{
printf(“ %d \n ”,count ) ; /* repeated action */
count -- ; /*update loop variable */
}
printf( “Done” ) ;
Count-controlled Loop
1. Priming
2. Test Condition
3. Update
9
• If we want to compute: we need to go 1+2+3+...+100
• We can use a while loop. /* computes the sum: 1 + 2 + 3 + ....+ 100 */
#include <stdio.h> int main(void) {
int sum =0, i = 1; while (i <= 100) {
sum = sum + i;
i = i + 1;
}
printf("Sum is %d\n", sum);
return 0;
}
Computing sum
100
1i
i
12
• A loop that never ends.
•Generally, you want to avoid these!
•There are special cases, however, when you do want to create infinite loops on purpose.
Infinite loop
13
#include <stdio.h>
#define MAX 10
main ()
{
int index =1;
while (index <= MAX)
{
printf ("Index: %d\n", index);
}
}
Infinite While Loop
1. Priming
2. Test Condition
3. Where is the update part
Index: 1
Index: 1
Index: 1
Index: 1
Index: 1
… [forever]
14
#include <stdio.h>
/* no MAX here */
main ()
{
int index =1;
while (index > 0)
{
printf ("Index: %d\n", index);
index = index + 1;
}
}
Infinite While Loop
1. Priming
2. Test Condition
3. Update
Index: 1
Index: 2
Index: 3
Index: 4
Index: 5
… [forever]
15
Basic for Loop Syntax
For loops are good for creating definite/counting loops.
int counter;
for (counter =1;counter <= 10;counter++)
printf ("%d\n", counter);
1. Priming: Set
the start value.
2. Test Condition:
Set the stop value.
3. Update: Update the
value.
Note that each section is
separated by a semicolon.
11
• To compute the sum of 1 to 100: int sum = 0;
int i;
for (i = 1; i <= 100; i++)
{
sum = sum + i;
}
• Note: i++ is the same as i = i + 1
and as i += 1.
for Statement Example
12
for (initialize; test; update)
{
//Steps to perform each iteration }
1. First, the initialization expression is executed. 2. Then, the loop repetition condition is tested. 3. If the condition is true, the statement enclosed in { } are executed. 4. After that the update expression is evaluated. 5. Then the loop repetition condition is retested.
• The statement is repeated as long as the condition is true. • For loop can be used to count up or down by any interval.
General form of for Statement
13
Increment and Decrement Operators
• The counting loops that we have seen have all included assignment expressions of the form counter = counter + 1 or counter++
or counter += 1
• This will add 1 to the variable counter. If we use a - instead of a +, it will subtract 1 from the variable counter.
• Be careful about using the ++ or -- options.
Increment and Decrement Other Than 1
• Instead of adding just 1, we can use sum = sum + x or sum += x
• Both of these will take the value of sum and add x to it and then assign the new value to sum.
14
• We can also use temp = temp -x or temp -= x
• Both of these will take the value of temp and subtract x from it and then assign the new value to temp.
15
• In many programming situations, we will not be able to determine the exact number of loop repetitions before loop execution begins.
• Next is an example where we do not know how many times our program will repeat.
Event/Conditional controlled
Loops
21
Event controlled loop Flag-controlled Loops
• How are they used?
– Programmer picks a value that would never be encountered for normal data
– User enters normal data and then when done,
enters the unusual value – The loop would stop when seeing the unusual
value
Example
• We need a program that prompts the user for a value and multiplies it by the value of the variable temp. It then stores the result in temp. It keeps doing this until the user enters a
0.
• The outline of the program would be as follows:
16
assign temp the value of 1
prompt the user for a value
while value does not equal 0
assign temp the value of temp times value prompt the user for a value
output the value of temp
Program Fragment
temp = 1;
printf("Enter a value, 0 will stop the program> ");
scanf("%d",&value);
while(value != 0) {
temp = temp * value; printf("Enter a value, 0 will stop the program>");
Initialization
Testing
17
scanf("%d",&value);
}
printf("The product is %d", temp);
Update
24
do-while Statement Is a looping control structure in which the loop
condition is tested after each iteration of the loop.
SYNTAX
do
{
Statements
} while ( Expression ) ;
Loop body statement can be a single statement or a block.
25
Computing Sum
If we want to compute , we need to go
1+2+3+...+100
/* computes the sum: 1 + 2 + 3 + ....+ 100 */
#include <stdio.h>
int main(void)
{
…..
……
……
printf("Sum is %d\n", sum);
return 0; }
100
1i
i
• Both the for statement and the while statement evaluate the loop condition before the first execution of the loop body.
• In most cases, this pretest is desirable and
18
prevents the loop from executing when there may be no data items to process
• There are some situations, generally involving interactive input, when we know that a loop must execute at least one time.
The do-while Statement
do-while Example
19
#include<stdio.h>
#define m_in_km 1.606
void main(){
float m,km;
char d;
do{
printf("Enter distance in miles> ");
scanf("%f",&m);
km=m_in_km * m;
printf("\n\n %f miles is %f kms\n",m,km);
printf("Do you want another conversion? <enter y to continiue>");
fflush(stdin); //in order for scanf( “%c”…) to work properly
scanf("%c",&d);
}while(d=='Y'||d=='y');
printf("thank you for using our software...");
}
28
do-while Loop vs. while Loop
POST-TEST loop
(exit-condition)
The looping condition
is tested after
executing the loop
body.
Loop body is always
executed at least
once.
PRE-TEST loop
(entry-condition)
The looping condition
is tested before
executing the loop
body.
Loop body may not be
executed at all.
20
• Usually used to work with two dimensional arrays (later).
• Nested loops consist of an outer loop with one or more inner loops.
• Each time the outer loop is repeated, the inner loops are reentered
– Their loop control expressions are reevaluated
– All required iterations are performed again.
Nested Loops
What is the Output? /* * Illustrates a pair of nested counting loops */ #include <stdio.h> Int main(void) {
21
int i, j; /* loop control variables */ printf(" I J\n"); for (i = 1; i < 4; i++) { printf("Outer %6d\n", i); for (j = 0; j < i; j++) { printf(" Inner%9d\n", j); } /* end of inner loop */ } /* end of outer loop */ return (0);
}
I
1 2 3
//output: Outer
Inner
Outer
Inner
Inner
Outer
Inner
Inner
Inner
J 0 0
1 0
1
2
Compound Assignment Operators
• Several times we have seen: variable = variable <operator> expression; Example: sum = sum + i;
• where <operator> is a C operator
22
• This occurs so often, C gives us short cuts.
• Instead of writing x = x +1 we can write: x += 1.
• We can use -=, *=, /=, and %= in the same way.
The End