Overview of C

advertisement
Problem Solving and Program Design in C
(5th Edition)
by Jeri R. Hanly and Elliot B. Koffman
Chapter 5
(Loop Statements)
© CPCS 202
12-10-1429
#
CHAPTER 5 - Loops
1.
2.
Chapter 5
3.
4.
1. Compound
Assignment
Operators
2. Repetition
and Loop
Statements
2a.
While
Statement
2b.
Do-While
Statement
5.
ATM Simulation 3
Company Payroll
Validating Numbers
Illustrate Nested Loop
Bald Eagle Sightings
2c.
For
Statement
 column shows the topics index.  column shows the programs index.
1
Compound Assignment Operators
A.
Introduction

B.
Giving programmers alternative ways to write equations
Syntax
1.
When an assignment statement in the form:
variable = variable op expression;
It can be written in the following format
variable op= expression;
2.
C.
If we try to increase/decrease the value of the variable by only
one, we can use increment (++) or decrement (--) operators
Examples
1.
2.
x = x * 5;
x = x + 1;
as same as
as same as
x *= 5;
x += 1;
as same as x++;
2
Repetition and Loop Statements
A.
Introduction



Loop repeats a group of statements until a condition is met
Avoid infinity loop
Each loop has a loop control variable, and three components:
1.
2.
3.

B.
Initialization of the loop control variable
Testing of the loop repetition condition
Changing (updating) of the loop control variable
Nested Loop is a concept of loops inside loops
Subtopics
1.
2.
3.
while Statement
do-while Statement
for Statement
2a
1. While Statement
Introduction


B.
The statement (loop body) is executed while the condition
(Loop repetition condition) is True
Avoid infinity loop
Syntax
while (loop repetition condition)
one statement
or
while (loop repetition condition)
{
statements
// loop body
}
Loop
Repetition
Condition
F
A
T
loop body
A.
B
C
Flow Diagram for (while)
P1
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
ATM Simulation 3

Write a program that simulates an ATM, where they are three
main options:
Deposit Money
2. Withdraw Money
3. Print Balance
1.




Assume the balance in the account is Zero
Use if to choose an option from the Main Menu
Validate the input; if a user choose a wrong option, display an
error message
REPEAT the menu until the user choose Zero
-6-
P1
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
ATM Simulation 3
1. #include <stdio.h>
2.
3. int main(void)
{
4.
int command, money, balance;
5.
6.
/* 1. Initial the balance */
7.
/* 2. Ask the user to choose
8.
9.
while (command != 0)
//
10.
{
11.
switch (command)
12.
{
13.
case 1:
/*
14.
15.
case 2:
/*
16.
17.
case 3:
/*
18.
19.
default:
20.
}
21.
}
22.
return(0);
23. }
one of the 4 options */
stop the loop if command = 0
2.1 Deposit Money */
2.2 Withdraw Money */
2.3 Print Balance */
P1
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
1. Initialization
2. Condit
1. #include <stdio.h>
2.
3. int main(void)
4. {
int command, money, balance;
5.
6.
/* 1. Initial the balance */
7.
balance = 0;
8.
9.
/* 2. Ask the user to choose one of the 4 options */
10.
printf("
Main Menu\n");
11.
printf("-----------------------\n");
12.
printf(" 0 - Exit\n");
13.
printf(" 1 - Deposit money\n");
14.
printf(" 2 - Withdraw money\n");
15.
printf(" 3 - Print balance\n");
16.
printf("Enter command number: ");
17.
scanf("%d", &command);
18.
19.
while (command != 0)
// stop the loop if command = 0
20.
{
21.
switch (command)
22.
{
23.
(loop control variable)
This loop will repeat based on the User Input
ATM Simulation 3
P1
Problem
Analysis
Design
Outline
ATM Simulation 3
Implementation
Testing
Maintenance
P2
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Company Payroll



Write a program that asks a user to choose the number of
employees in a company
The program calculates the payroll for each employee
according to the number of working hours and the rate
Also, the program calculates the total amount of money for all
the employees
-10-
P2
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
(loop control variable)
1. #include <stdio.h>
2.
3. int main(void)
4. {
double total_pay;
/* company payroll
*/
5.
int count_emp;
/* current employee
*/
6.
int number_emp;
/* number of employees */
7.
double hours;
/* hours worked
*/
8.
double rate;
/* hourly rate
*/
9.
double pay;
/* pay for this period */
10.
11.
/* Get number of employees. */
12.
printf( "Enter number of employees> ");
13.
scanf("%d", &number_emp);
14.
15.
/* compute each employee's pay and add it to the payroll */
16.
total_pay = 0.0;
17.
count_emp = 0;
18.
while (count_emp < number_emp)
19.
{
20.
printf("Hours> ");
21.
scanf("%lf", &hours);
22.
printf("Rate > $");
23.
1. initialization
This loop will repeat based on a counter
Company Payroll
2. cond
P2
Problem
Design
Analysis
Outline
Testing
Implementation
Company Payroll
statement
hours rate
?
count_emp < number_emp
scanf(“%lf”,&hours);
scanf(“%lf”,&rate);
?
pay
?
total_pay count_emp number_emp
0.0
Round 1
50.0
5.25
Pay = hours * rate;
262.5
total_pay = total_pay + pay;
262.5
count_emp = count_emp +1;
count_emp < number_emp
scanf(“%lf”,&hours);
scanf(“%lf”,&rate);
Pay = hours * rate;
1
Round 2
6.0
5.0
30.0
total_pay = total_pay + pay;
292.5
count_emp = count_emp +1;
count_emp < number_emp
scanf(“%lf”,&hours);
scanf(“%lf”,&rate);
Pay = hours * rate;
total_pay = total_pay + pay;
count_emp = count_emp +1;
0
2
Round 3
15.0
7.0
105.0
397.5
3
3
Maintenance
2b
2. Do-While Statement
Introduction

B.
The statement (loop body) is executed
once before checking the condition
Syntax
loop body
A.
2b
A
B
do
one statement
while (loop repetition condition);
or
do
{
statements
// loop body
} while (loop repetition condition);
condition
F
C
Flow Diagram
for (do-while)
T
2b
2. Do-While Statement
2b
C. Example
1.
2.
3.
4.
5.
6.
7.
8.
char letter;
do {
printf("Enter a letter from A through E to exit: ");
scanf(“%c", &letter);
} while (letter < ‘A’ || letter > ‘E’);
printf(“END...\n");
1
4-5
6
T
F
8
14
P3
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Validating Numbers


We need a program that asks a user to choose a value from
the range 10 to 20
Validate the input and display an error message if a user
chooses a number out of the range, a character, or an string
-15-
P3
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Validating Numbers
Go
tothe
the
function
In this case,
3 ways
tomain()
validate
the input
Check
first
1. #include <stdio.h>
2.
1. not a number
3. int get_int(int n_min,int n_max)
4. {
5.
int in_val,
/* input - number entered by user
*/
6.
status;
/* status value returned by scanf
*/
7.
char skip_ch;
/* character to skip
*/
8.
int error;
/* error flag for bad input
*/
9.
10.
/* Get data from user until in_val is in the range.
*/
11.
2. not in the range
do
12.
{
13.
error=0;
// No errors detected yet.
14.
15.
/* 1. Get a number from the user.
*/
16.
printf("Enter an integer in the range from %d ",n_min);
3. Skip the extra
17.
printf("to %d inclusive> ", n_max);
18.
status=scanf("%d", &in_val);
19.
printf("status = %d ", status);
20.
21.
/* 2. Validate the number
*/
22.
if(status!=1)
23.
{
P3
Problem
Analysis
Design
Outline
Implementation
Validating Numbers
Testing
Maintenance
2c
3. For Statement
Introduction

B.
Put the three main components in one
line in the same order
initial
Syntax
for (initialization expression;
loop repetition condition;
update expression)
{
statements
// loop body
}
update
condition
T
F
A
loop body
A.
2c
B
C
Flow Diagram for (for)
2c
3. For Statement
C. Example
1
5. /* display N asterisks */
6. for (count_star = 0; count_star < N; count_star += 1)
7.
printf(“*");
C. Example
2
5. int factorial(int n)
6. {
7.
int i, product;
8.
product = 1;
9.
10.
/* computes the product n x (n-1) x (n-2) x ... x 2 x 1 */
11.
for (i = n; i > l; i--)
12.
{
13.
product = product * i;
14.
}
15.
16.
return (product);
17. }
19
P4
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Illustrate Nested Loop



Write a simple program that illustrates how is nested loop
working.
Choose the outer loop from 1 to 3
Choose the inner loop from 0 to the outer number
-20-
P4
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Illustrate Nested Loop
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
/*
* Illustrates a pair of nested counting loops
*/
#include <stdio.h>
int main(void)
{
int i, j;
printf ("
I
J\n");
printf ("-------- --- ---\n");
for (i = 1; i<4; ++i)
/* heading of outer loop
{
printf("Outer %6d\n", i);
for (j=0; j<i; ++j)
/* heading of inner loop
{
printf("
Inner%9d\n", j);
} // end of inner loop
} // end of outer loop
return(0);
}
*/
*/
P5
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Bald Eagle Sightings



Write a program that calculates the number of bald eagle
appears in each month for one year
In each month, the user will enter the number of the bald
eagles in groups, such as 5 6 2 3 13 2
When a sentinel is appeared in a month, this indicates that no
bald eagle will appear in that month
bald eagle
-22-
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Bald Eagle Sightings
loop based on a USER INPUT
loop based on a COUNTER
P5
Month 1
5
8
2
0
Month 2
5
3
1
4
Month 3
1
0
0
Month 12
-23-
P5
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Bald Eagle Sightings
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
#include <stdio.h>
#define SENTINEL
0
#define NUM_MONTHS 12
int main(void)
{
int month,
mem_sight,
sightings;
/* number of month being processed
*/
/* one member's sightings for this month */
/* total sightings so far for this month */
printf("BALD EAGLE SIGHTINGS\n");
for (month = 1; month <= NUM_MONTHS; ++month)
{
sightings = 0;
scanf("%d", &mem_sight);
while (mem_sight !=SENTINEL)
{
if (mem_sight >= 0)
sightings += mem_sight;
else
printf("warning, negative count ignored\n");
scanf("%d", &mem_sight);
P5
Problem
Analysis
Design
Outline
Implementation
Testing
Maintenance
Bald Eagle Sightings

P5
Click on any character to move to the next scanf, such as Space or Enter
Q
Questions
1.
Which of the following is an infinite loop?
a)
b)
c)
d)
2.
for
for
for
for
(int
(int
(int
(int
i=20; i>=10; i--)
i=1; i<=10; i++)
i=10; i<=20; i--)
i=20; i>=50; i++)
The statement _______, when executed in a while loop,
skips the remaining statements in the body of the
structure and begins the next iteration of the loop.
a)
b)
c)
d)
continue
break
next
do/more
-26-
hw
Homework

Write a program to process 5 collections of daily high
temperatures using loop.Your program should count and
print:



the number of hot days (85 or higher),
the number of pleasant days (60-84), and
the number of cold days (less than 60).
It should also display the category of each temperature.
At the end of the run, display the average temperature.
HANDWRITING IN THE HOMEWORK IS NOT ACCEPTABLE
-27-
Download