Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture 5 Loops

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

C Programming Language

OUTLINE

Repetition and Loop Statements


Arrays
Multi-Dimensional Arrays
Repetition and Loop
Statements
Categories of Flow Controls

•Relational, Equality, Logical Operators are provided


to facilitate flow controls.
•Sequential - Statements in a program are executed
one after another.
•Selection - A choice of alternative actions (if, if-else,
and switch).
•Repetition - Repeat certain actions (while, for, and do).

3
Loops

So far our programs are very limited - they can only run
“straight through” the code.

But many situations require programs to repeat actions.

Repeating actions is called iteration

The control structures that we use to perform iteration are


called loops - we speak of programs “looping”.

4
A “loop” is a repeated (“iterated”) sequence of
statements.
Like conditionals, loops let us control the flow of our
program in powerful ways.
Like functions, loops take code that has been generalized
and execute it many times.

Block of code
within loop is
known as the
loop body

5
We will study three types of loops:

- while loops
- for loops
- do…while loops

We will also look at nested loops - what happens when


you put one loop inside another

6
• Counter-controlled repetition
– Definite repetition: know how many times
loop will execute
– Control variable used to count repetitions
• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not known
– Sentinel value indicates "end of data"

7
• Counter-controlled repetition requires
– The name of a control variable (or loop counter).
– The initial value of the control variable.
– A condition that tests for the final value of the
control variable (i.e. whether looping should
continue).
– An increment (or decrement) by which the control
variable is modified each time through the loop.

8
loop repetition condition
The while loop
The syntax is
while (condition) {
statements; loop body
} Note indentation!
Its meaning is
(a) evaluate the condition
(b) if its value is true (i.e., not zero) do the statements, and go
back to (a)
The while loop will repeatedly execute the statements in
the loop body until the condition is false.
Something in the body of the while loop must change
the condition, or the loop will never end!
9
Steps in using while loop

1. Initialize loop count (loop control variable)

2. Test loop repetition condition for termination

3. Update loop count

10
Example - Add five integers:

int i = 0; // initialize i
int temp, sum = 0; // initialize sum
while (i < 5) { // test if i < 5
scanf(“%d”, &temp); // read an integer
sum = sum + temp; // add to sum
i++; // increment i
}
Important to initialize the loop count before starting the
loop, and to increment the count within the loop.

11
Example - Accumulating a sum

int sum, x, count;


int number_inputs; /* Number of inputs */

sum = 0;
printf("How many numbers? ");
scanf("%d", &number_inputs);
printf("Enter %d numbers: ", number_inputs);
count = 1;
Initialization
while ( count <= number_inputs ) {
scanf("%d", &x);
sum = sum + x; Condition
count = count + 1;
}
Update

12
Example - Calculate pay

count_emp = 0; /* no employees processed yet */


while (count_emp < num_emp) { /* test value of count_emp */
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; /* increment count_emp */
}
printf("\nAll employees processed\n");

13
Example - Computing a Factorial

7! = 1 * 2 * 3 * 4 * 5 * 6 * 7
We could write this without a loop (Yuck!). But easier to
write it with a loop.
x = 1 * 2 * 3 * 4 * 5 * 6 * 7;
printf ( "%d", x ) ;
int i = 1;
int product = 1;
while(i <= 7){
product = product * i;
i++;
}

14
Example - Factorial Function

Even better if we generalize the algorithm and make it in


to a function. Can compute N!

int fact(int number){


int i = 1; Local variables -
re-initialized at each
int product = 1; call
while(i <= number){
product = product * i;
i++;
}
return product;
}

15
Infinite Loop Using while
while (1)
statement;
next statement;

•Stop the program in the operating system level, for


example, Ctrl-C or Ctrl+Break in DOS.
•There is a break statement for terminating the loop
(discussed later).
•Use carefully!

16
The for Loop

The syntax is

for ( initialization ; condition; update ) {


statements;
}

Note that the for loop statement, as well as having a


condition, has an initialization and an update part also.
Another construct for doing the same thing - iteration.

17
If the initialization, condition and/or update parts are
long, place each on a separate line for clarity.

for ( initialization;
condition;
update ) {
statements;
} Execution Steps:
next_statement; 1. initialization
2. condition expression is evaluated.
- if true,
(a) statements are executed.
(b) update expression is executed.
(c) goto step (2) again.
- if false, next statement is executed.

18
for loop versus while loop

for and while loops can always be interchanged …


but some cases are much better suited to for loops
than while loops.

i = 0;
while (i < 10) { for(i = 0; i < 10; i++) {
printf(“%d\n”, i); printf(“%d\n”, i);
i++; }
}

19
Which Loop Should You Choose?

They are interchangeable, so to some extent it is


personal preference.
Use the for loop if you know how many times you
are going to do something.
Think which construct will yield the simplest,
clearest code.

20
Example
total_pay = 0.0;
for (count_emp = 0; /* initialization */
count_emp < number_emp; /* loop repetition condition */
count_emp += 1) { /* update */
printf("Hours> ");
scanf("%lf", &hours);
printf("Rate > $");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n\n", pay);
total_pay = total_pay + pay;
}
printf("All employees processed\n");
printf("Total payroll is $%8.2f\n", total_pay);

21
Example - Factorial

int factorial(int n)
{
int i, /* local variables */
product; /* accumulator for product computation */

product = 1; Note that we may


decrement or
for (i = n; i > 1; --i) {
increment the loop
product = product * i; count
} - it depends on how
return (product); we write the
initialization
}
and condition parts

22
Increments and decrements other than one

Not obliged to increment / decrement the loop count


by 1.

May use any value.

23
Infinite Loop Using for

for (;;) {
statements;
}
•Stop the program in the operating system level, for
example, Ctrl-C or Ctrl+Break in DOS.
•There is a break statement for terminating the loop
(discussed later).
•Use carefully!

24
Example - Celsius / Fahrenheit table
#define CBEGIN 10
#define CLIMIT -5
#define CSTEP 5

/* Variable declarations */
int celsius;
double fahrenheit;

/* Display the table heading */


printf(" Celsius Fahrenheit\n");

/* Display the table */


for (celsius = CBEGIN;
celsius >= CLIMIT;
celsius -= CSTEP) {
fahrenheit = 1.8 * celsius + 32.0;
printf("%6c%3d%8c%7.2f\n", ' ',
celsius,
' ', fahrenheit);
}
Practice: C-to-F-table-part.c 25
The Comma Operator and for
expr1 , expr2

• Lowest precedence of all operators.


• Left-to-right associativity.
• Value of expr2 taken as value of the whole expression.
• Example, a = 0 , b = 1;
• Example
for (i=1, factorial=1; i<=n; i++)
factorial *= i;

26
Conditional Loops

In some situations, you may not know the exact number


of loop iterations required.

It is still possible to write a loop in such circumstances.

Steps:

1. Initialize loop control variable


2. As long as exit condition has not been met
3. Continue processing

27
Loop Design
Sentinel-controlled Loops

Input a list of data values of any length, terminated by


a special (sentinel) value.

double variable; /* current input */


declarations;
initial statements;
scanf("%lf", &variable);
while (variable is not equal to sentinel){
process;
scanf("%lf", &variable);
}
final statements;
28
Example - Average Inputs

printf ( "Enter values to average, end with -1.0 \n") ;


sum = 0.0 ;
count = 0 ;
scanf ( "%lf", &next ) ;
while ( next != -1.0 ) { Loop terminates when a
sum = sum + next ; sentinel value (-1) is
count = count + 1; entered at keyboard
scanf ( "%lf", &next ) ;
Comments
}
if (count > 0)
printf( "The average is %f. \n", sum / (double) count );

29
Endfile-controlled Loops

Input from a file of data and do not know how many data
items there are.

Files have a special marker to indicate the end of data -


end-of-file (eof) marker

Condition to terminate loop can be controlled by using


the eof marker

- in C, the eof marker is denoted by the reserved


word, EOF

30
Example

sum = 0;
input_status = fscanf(inp, "%d", &score);
while (input_status != EOF) {
printf("%5d\n", score);
sum += score;
input_status = fscanf(inp, "%d", &score);
}

31
Nested Loops

How would you print the following diagram?

*****
*****
*****

Solution:
repeat 3 times
print a row of 5 *s repeat 5 times
print *
print newline

It seems as if a loop within a loop is needed!


32
When you put one loop inside another, then you
have nested loops

Nested loops can be much more confusing than


single loops!

33
#define ROWS 3
#define COLS 5

row = 1;
while ( row <= ROWS ) {
/* print a row of COLS *s */
...
row = row + 1;
}

34
#define ROWS 3
#define COLS 5
row = 1;
while ( row <= ROWS ) {
/* print a row of 5 *s */
col = 1;
while (col <= COLS) {
printf("*"); Outer loop -
Inner loop -
col = col + 1; print three
print one row
} rows
printf( "\n" );
row = row + 1;
}

35
#define ROWS 3
#define COLS 5
outer loop - print 3 rows
...
for ( row = 1; row <= ROWS ; row = row + 1 ) {
for ( col = 1 ; col <= COLS ; col = col + 1 ) {
printf(“*”);
}
printf( "\n" ); inner loop - print one
row
}

36
How would you print the following diagram?
*
**
Solution:
***
for every row ( row = 1, 2, 3, 4, 5 ) ****

print row stars *****

#define ROWS 5
...
int row, col ;
for ( row = 1 ; row <= ROWS ; row = row + 1 ) {
for ( col = 1 ; col <= row ; col = col + 1)
{
printf( “*” ) ;
}
printf( "\n" );
}
37
Remember the function to print rows of asterisks
between lines of output?

Now we can write a generalized function:

void print_banner( int lines, int numchar, char ch ) {

int i, j ;

for ( i = 0 ; i < lines ; i = i + 1 ) {

for ( j = 0 ; j < numchar ; j = j + 1 )


printf ( "%c", ch);
}

print (“\n”);
}

}
38
Exercise
Study and execute the following
#include <stdio.h> program.
#define N 7
int main(void)
{
int cnt = 0, i, j, k;
for (i = 0; i <= N; ++i)
for (j = 0; j <= N; ++j)
for (k = 0; k <= N; ++k)
if (i + j + k == N) {
++cnt;
printf("%3d%3d%3d\n", i, j, k);
}
printf("\nCount: %d\n", cnt);
return (0);
}

39
do...while loop

The do…while loop is like a while loop, but it does the


condition test at the end of the loop
⇒ all statements in loop body are executed at least
once

This can be very useful for doing things like checking


user input.

40
41
Example

Checking user input:

do {
printf(“Enter your age: “);
scanf(“%d”, &age);
} while (age < 0);

42
Example
counter = 1;
do {
printf( "%d ", counter );
} while (++counter <= 10);

Example - sum the digits of a positive number

sum = 0;
do {
sum += n % 10;
n /= 10;
}
while(n > 0);

printf("The sum of the digits is =


%d\n", sum);
43
#include <stdio.h> while condition
void main(){
int n, sum;
while ( (printf("Enter number = ") && scanf("%d",&n) && n) != 0 )
{
sum = 0; true (1) true (1)
do { false (n==0)
sum += n % 10; true (n != 0)
n /= 10;
}
while(n > 0);
printf("The sum of the digits is = %d\n", sum);
}
}
Practice: sum-digit.c
44
Controlling Repetition
break and while #include <stdio.h>
Causes an exit from the innermost enclosing loop. #include <math.h>
int main(void)
{
int x;
while (1) {
scanf("%d", &x);
If (x < 0)
break;
printf ("square root = %.2f\n",
sqrt(x));
}
printf ("Bye!\n");
return (0);
}

45
Controlling Repetition …
break and for #include <stdio.h>
Causes an exit from the innermost enclosing loop. int main(void)

Will update be executed before leaving the for {


loop? int i, x;
for (i=0; i<10; i++) {
printf("i = %d\t", i);
printf("x = ? ");
i=0 x = ? 10 scanf("%d", &x);
i=1 x = ? 20 if (x==0)
i=2 x=?4
break;
i=3 x=?5
i=4 x=?0 }
After the loop, i = 4 printf("After the loop, i = %d\n", i);
Bye! printf ("Bye!\n");
return (0);
}

46
Controlling Repetition …
continue
Causes the current iteration of
a loop to stop, and begins
the next iteration.
#include <stdio.h>
#define MAX 5
int main(void)
{
int data, sum=0, k;
for (k=0; k<MAX; k++) {
scanf ("%d", &data); 10
if (data <= 0) 20
continue;
-1
sum += data;
} 90
printf ("Sum of positive values is %d\n.", sum); -5
return (0); Sum of positive values is 120.
}

47
How to debug and test programs
• Debugger Program
– Single-step execution (F8)
– Add Watch-window (Alt+W W)
– Breakpoints
• Debugging without a debugger
– Insert additional diagnostic calls to printf to trace the values
of critical values
#define DEBUG 0
if (DEBUG)
printf ……

48
Common Programming errors

• Off-by-One Loop errors

for (i =0; i<n; i++) Loop body is executed n times

sum+= i;

for (i =0; i<=n; i++) Loop body is executed n+1 times


sum+= i;
49
Common Programming errors …
Syntax of the for statement
for (initialization expression;
loop repetition condition;
update expression )

Do not put ; here

Always use braces around the loop body, whether it


contains one or many statements

50
Common Programming errors …
• Be careful when testing for inequality (!=) to
control repetition of a loop (infinite loop may
result)
• In sentinel-controlled loop:
– Provide a prompt to program’s user what value to
enter as sentinel
– Make sure that the sentinel value cannot be
confused with a normal data item
• Do not mistype equality test (==) and
assignment operator (=)
51

You might also like