Você está na página 1de 21

THE WHILE STATEMENT

Simulating the for statement

The while construct may be used to simulate


the for statement.
Consider the following program which we
encountered earlier:

The Program
//
//
//
//
//

This simple program illustrates the use of the for statement.


For each of 4 employees, it reads in a salary and computes tax,
health surcharge and NIS. If the salary is less than or equal to $50,000,
then tax, health and NIS are computed at rates which are lower
than if the salary exceeds $50,000.

#include <stdio.h>
void main()
{
double salary, tax, health, NIS;
int i;
// looping variable in the for statement
for (i = 1; i <= 4; i += 1)
{
printf_s("Enter salary \n");
scanf_s ("%lf", &salary);
if (salary > 50000)
{
tax = 0.35 * salary;
health = 0.05 * salary;
NIS = 0.02 * salary;
}
else
{
tax = 0.28 * salary;
health = 0.035 * salary;
NIS = 0.015 * salary;
}

printf_s("Tax = %8.2f \n", tax);


printf_s("Health insurance = %8.2f \n", health);
printf_s("NIS = %8.2f \n", NIS);
} // brace to end the for statement

Example simulating the for statement


// This simple program illustrates how the while statement
// may be used to simulate the for statement. For each of 4
// employees, it reads in a salary and computes tax, health
// surcharge and NIS. If the salary is less than or equal to $50,000,
// then tax, health and NIS are computed at rates which are lower
// than if the salary exceeds $50,000.
#include <stdio.h>
void main()
{
double salary, tax, health, NIS;
int counter;
// counter variable used in the while statement
counter = 0;
while (counter < 4)
{
printf_s("Enter salary \n");
scanf_s ("%lf", &salary);
if (salary > 50000)
{
tax = 0.35 * salary;
health = 0.05 * salary;
NIS = 0.02 * salary;
}
else
{
tax = 0.28 * salary;
health = 0.035 * salary;
NIS = 0.015 * salary;
}
printf_s("Tax = %8.2f \n", tax);
printf_s("Health insurance = %8.2f \n", health);
printf_s("NIS = %8.2f \n", NIS);
counter += 1;
} // brace to end the while statement
}

Other Uses of the while statement

The while construct is most useful for situations in


which you do NOT know the number of times the
loop will be executed.
E.g.

Processing the customers at a check-out counter


Operations at an ABM machine

Consider the following problem:


A person earns 1 cent on the first day on a job, 2 cents
on the next, 4 cents on the next, etc. In other words, on
each day his salary is twice that of the previous day. On
which day will his salary equal or exceed $100.00

The Solution
The solution should have the following format:
DAY
1
2
3
4
5
6
7
8
9
10
11
12
13
14

SALARY
0.01
0.02
0.04
0.08
0.16
0.32
0.64
1.28
2.56
5.12
10.24
20.48
40.96
81.92

The following program produces the above output.

The Program
//
//
//
//
//
//

This program solves the following problem.


A person earns one cent on the first day on a job,
two cents on the second day, four cents on the third, etc.
In other words, on each day his salary is twice that of the
previous day. On which day will his salary equal or exceed
one hundred dollars?

#include <stdio.h>
void main()
{
int day = 1;
double salary = 0.01;
printf_s("DAY

SALARY \n\n"); // heading

while (salary < 100)


{
printf_s("%d\t\t%.2f\n", day, salary);
day += 1;
salary *=2;
}

Sentinel-Controlled loops

The while statement may also be used to


implement sentinel-controlled loops.
A sentinel is a special data value that may be
used to halt the looping process.
E.g., if you are entering a set of grades, then
a grade of -1 may be a signal to stop the
looping all valid data has been entered.
We now write a program to enter a set of
grades until a grade of -1 is entered. After all
valid grades are entered, output the class
average.

The Program
//
//
//
//

This program illustrates the implementation of a sentinel


controlled loop. It accepsts as input a set of grades
until a grade of -1 is entered. It determines the average
of the grades.

#include <stdio.h>
void main()
{
int grade;
double sum = 0;
double average;
int num = 0;

//
//
//
//

input
to hold the sum of the grades
to hold the average
to hold the number of grades

printf_s("Enter first grade \n");


scanf_s ("%d", &grade);
while (grade != -1)
{
sum += grade;
num += 1;

printf_s("Enter next grade \n");


scanf_s ("%d", &grade);

average = (double) sum / num;


printf_s("Average = %8.2f \n", average);

Must read
before the
loop

Read
again at
end of
loop

Exercise
Write a program which uses a sentinel
controlled loop to enter a set of alphabetic
characters, and to output the number of
vowels and the number of consonants entered.
Use the period as the sentinel to halt the
looping.

Response Controlled Loops


A third type of loop that is handled via the while statement is
the Response Controlled loop. (Recall that the other two
types are Conditional loops and Sentinel Controlled loops.)
A Response Controlled loop is one which prompts the user to
enter Y or N to indicate whether or not he wants to continue
looping. This type of looping is common in ABM machines.
Looping halts when the user enters N.
E.g., Develop a program which uses a response-controlled
loop to enter an id, program and number of credits for each
of a set of students. The program may be IT (I), Electrical
(E), or Mechanical (M). IT programs cost $200 per credit,
Electrical costs $250 and Mechanical costs $195. The
program displays the total cost for each student. It also
accumulates the costs for all students and displays this cost.

The Program
//
//
//
//
//
//
//
//

This program uses a response-controlled loop to enter


an id, program and number of credits for each of a set
of students. The program may be IT (I), Electrical (E),
or Mechanical (M). IT programs cost $200 per credit,
Electrical costs $250 per credit and Mechanical costs
$195 per credit. The program displays the total cost
for each student. It also accumulates the costs for all
students and displays this cost.

#include <stdio.h>
void main()
{
int id;
char program;
int numCredits;
double cost, totCost = 0;
char response = 'Y';
char dummy;
// To catch the carriage return

\n");

cost = 200 * numCredits;


cost = 250 * numCredits;
cost = 195 * numCredits;
printf_s("Invalid program

return;
}
totCost += cost;

printf_s("Cost for student = %8.2f \n", cost);


//Get ready for next student
printf_s("Any more students - Y or N \n");
scanf_s ("%c", &response, 1);
} // end of the while loop

while (response == 'Y')


{
printf_s("Enter id \n");
scanf_s ("%d", &id);
printf_s("Enter program \n");
scanf_s ("%c", &program, 1);
printf_s("Enter num. credits \n");
scanf_s ("%d", &numCredits);

switch (program)
{
case 'i':
case 'I':
break;
case 'e':
case 'E':
break;
case 'm':
case 'M':
break;
default:

// Display the grand total

printf_s("Total cost for all students = %8.2f \n", totCost);

Modifications to last program

What would happen if the user does not enter I, E or M for


the program?
How can we ensure that the user enters only I, E or M?
The following code excerpt shows how to validate this entry:
program = toupper(program);

while (!(program == 'I' || program == 'E' || program == 'M'))


{
printf_s("Invalid program - re-enter \n");
scanf_s ("%c", &program, 1);
program = toupper(program);
}
You must include <ctype.h> in order to use toupper.
Note that we now have a loop within another loop

Exercise
This question deals with simulating a cash register at a grocery store. For each of a set of items purchased
by a customer, you are to enter the item code of the item (int), the number of units of the item purchased
and the unit price of the item. Your program should then determine and display the total for the item
purchased. Your program should also accumulate these totals in order to determine the grand total payable
by the customer. The grand total payable by the customer should also be displayed.

You do not know how many items are purchased by the customer. Your procedure must use a responsecontrolled loop to handle the looping.
Use the following data when running your program:

Item Code

Num. Units

Unit Price

1250
1376
2872
5839
8586
5834

5
7
3
2
2
3

12.50
3.75
2.75
12.87
89.50
9.45

Nested Loops

As the name suggests, a nested loop is a loop


inside another loop.
An example of the format of a nested for loop is:
for (i = 1; i <= 10; i += 1)
{
This loop is
nested
for (j = 1; j <= 8; j += 1)
{
.
.
.
}
}

Nested Loops Continued


An example of the format of a nested while loop is:
while (response1 == Y)
{
.
.
.
while (response2 == Y)
{
.
.
.
}

.
.
.

This loop is
nested

Example of nested loop

Recall an earlier exercise about processing


the items of a customer at a grocery store.
We now want to extend this exercise to
several customers.
Just as we did not know the number of items
of a customer, so too we do not know the
number of customers.
Here is a picture of the situation we have.

The Output
After processing the data for each customer,
your program should ask if there are any more
customers. If the response is Y, then go on to
process the next customer.

//
//
//
//
//

This program processes the data for a series of customers


at a grocery store. Each customer has several items. The
number of items for a customer is unknown, and the number
of customers is unknown. The program prompts for more
items for each customer, as well as for more customers.

printf_s("Any more items - Y / N? \n");


scanf_s ("%c", &response2, 1);
response2 = toupper(response2);
// Validate response2
while (!(response2 == 'Y' || response2 == 'N'))
{
printf_s("Invalid response. Use Y / N only \n");
scanf_s ("%c", &response2, 1);

#include <stdio.h>
#include <ctype.h>
void main()
{
int itemCode;
int numUnits;
double unitPrice, extPrice, totalPrice;
char response1 = 'Y';
// to control outer loop
char response2;
// to control inner loop
char dummy;
// to catch carriage return

response2 = toupper(response2);
}
} // end of inner loop
// Print total for customer
printf_s("Total owing = %8.2f \n\n", totalPrice);

while (response1 == 'Y')


{
totalPrice = 0;
response2 = 'Y';
while (response2 == 'Y')
{
printf_s("Enter item code \n");
scanf_s ("%d", &itemCode);
printf_s("Enter # of units \n");
scanf_s ("%d", &numUnits);
printf_s("Enter unit price \n");
scanf_s ("%lf", &unitPrice);
extPrice = numUnits * unitPrice;
totalPrice += extPrice;

// ask for more customers


printf_s("Any more customers - Y / N? \n");
scanf_s ("%c", &response1, 1);
// Validate response2
response1 = toupper(response1);
while (!(response1 == 'Y' || response1 == 'N'))
{
printf_s("Invalid response. Use Y / N only \n");
scanf_s ("%c", &response1, 1);
response1 = toupper(response1);
}
} // end of outer loop
}

ASSIGNMENT

Você também pode gostar