Transcript While

IPC144 - LOOPS
while
- do while
- for
Review - SWITCH

The switch statement can also be used to select
code to be executed and code to be skipped. It
does not handle ranges. It does not loop.
switch ( expression )
/* expression must be integer or single character */
{
case (constant): statement(s); break;
case (constant): statement(s); break;
default: statement(s);
/* optional */
}
SWITCH used in Banking Pgm

Consider the situation of opening a new bank account.
char account_type;
printf(“ Type of account? c … chequing\n”);
printf(“ s … savings\n”);
scanf(“ %c”, &account_type);
switch (account_type)
{
case ‘c’: int_rate = 0.005; gift = 50.00; break;
case ‘s’: int_rate = 0.025; gift = 100.00; break;
default: int_rate = 0.0; gift = 50.00;
}
SWITCH – Two cases with the same
outcome We can join cases together if the code block is the same.
Notice that case ‘c’ chequing and case ‘s’ saving have identical code
blocks because there is no break statement.
The switch statement could be written as:
switch (account_type)
{
case ‘c’:
case ‘s’:
int_rate = 0.005;
gift = 50.00;
break;
default:
int_rate = 0.0;
gift = 25.00;
}
switch – Prog Question 6-4
Use the switch statement to program
the following:
SmartKeySystems wants to hire a
Systems Analyst. They give each
resume received a value from 1.5 to
3.5 for education and another value
(1.5-3.5) for work experience. The
numbers are added to get a total
score. The score is rounded to the
nearest integer. Here is what they
do:
Note: switch cannot be used for
doubles – only int or char!
3
Nothing
4-5
Keep the
resume on
file
Send a thank
you letter
Schedule an
interview
6
7
switch Prog Ques 4 –ans




















#include<stdio.h>
main()
{
double total,educ,work;
int i;
printf("Enter the score for education: ");
scanf("%lf",&educ);
printf("Enter the score for work experience: "); scanf("%lf",&work);
total = educ+work;
total = total + .5;
/* prepare to round */
i = total;
switch (i)
{
case 3: printf("Do not send a response\n"; break;
case 4:
case 5: printf("Keep on file\n"; break;
case 6: printf("Send a thank you letter\n", break;
case 7: printf("Schedule Interview\n"); break;
default:
}
}
Summary of steps taken by the
switch statement.



1)
2)
3)
evaluate the expression.
search to find matching case.
if a match is found, execute the instructions until…





4)

5)
- a break statement is reached
- or a default statement is reached
- or a } brace ending the switch statement is reached.
At that point go to the statement following the switch statement.
If there is no match and there is a default code block,
perform the default code block.
if there is no match and there is no default code block, exit
the switch statement and continue program execution with
the first statement following the switch statement.
Comments on switch
Notes:
1)
2)
3)
no
The default section is optional.
break is needed to prevent one case from running into an other.
no code whatsoever will be performed if the is no match and there is
default section.
4) Discussion Question:
Is switch preferable to an if - else if - else if - else?
 Readability: Switch / Case is usually better.
 Speed: Switch is faster.
 Flexibility: If / Else / Else If using ANDs/ ORs is usually
better.
Walkthrough 7-1
What is the expected output of the following
pgm?
int x=5; y=10; z=15;
switch (z){
case 2: printf(“case
case 4: printf(“case
case 5: printf(“case
default: printf(“The
}
2 is executing\n”); break
4 is executing\n”);
5 is executing\n”); break;
default is executing\n”);
Walkthrough 7-2
What is the expected output of the following
pgm?
int x=5; y=10; z=15;
switch (y/x){
case 2: printf(“case
case 4: printf(“case
case 5: printf(“case
default: printf(“The
}
2 is executing\n”); break;
4 is executing\n”);
5 is executing\n”); break;
default is executing\n”);
Walkthrough 7-3
What is the expected output of the following
pgm?
int x=5; y=10; z=15;
switch (x-1){
case 2: printf(“case 2 is executing\n”); break;
case 4: printf(“case 4 is executing\n”);
case 5: printf(“case 5 is executing\n”); break;
default: printf(“The default is executing\n”);
}
Prog Question 7-5
The cost of 10 corn depends on the month.
In July (month 7) it is $3.75
In August (month 8) it is $4.25
The user enters the month number.
We can can use switch or if.
Which one is better?
Prog Question 7-5- Ans
Switch is better because it will run faster.
In a simple case like this, it is very readable.
printf(“Enter the month number:”);
scanf(“%d”, &month);
switch (month){
case 7: price = 3.75; break;
case 8: price = 4.25;
}
Prog Question 7-6
The cost of 10 corn
depends on the month
and the grade.
Use a switch to select the
correct month and
within each case, use an
if to select the right
price.
The user enters the month
number and the grade
number.
Month Grade A Grade B
Number
=1
=2
7
(July)
$3.50
$2.85
8
$4.00
(August)
$3.05
Prog Question 7-6 - Ans
printf(“Enter the month and grade numbers separated by a
space:”);
scanf(“%d %d”, &month, &grade);
switch (month){
case 7:
if (grade == 1)
price = 3.50;
else
price = 2.85;
break;
case 8:
if (grade == 1)
price = 4.00;
else
price = 3.05;
}
While
To perform some code repeatedly
Write a program to print odd numbers between 50 and 100.
The program prints the number, the square of the number and the cube of the
number.
k=51;
while(k<100){
printf(“%d square: %d cube: %d\n”, k,
k = k + 2;
}
printf (“ All done\n”);
k*k,
k*k*k );
Prog 7-7 – Pie Eating
While – Perform statements repeatedly
A person is practicing for a pie-eating contest.
They start with a pie of 750 grams. Each day
they eat 10% more than the previous day.
How many days will it take to get to the goal of 2
kilograms?
Prog 7-7 – Pie Eating - Ans
While – Perform statements repeatedly
#include<stdio.h>
main()
{
int days = 0;
double grams = 750;
while(grams < 2000){
grams = grams * 1.1; /* to add 10 % */
days = days + 1;
printf("On day %d you ate %.2lf grams\n",days+1,grams);
}
printf("It took you %d days to get to your goal\n", days+1);
}
While – Walkthrough 4
What is the expected output?
int i=3,k=25;
double x = 0.2;
while ( k/i > 0){
x=x+0.3;
k=k-4;
i=i+x-1;
printf(“The current value of k/i is: %d \n”, k/i);
}
}
While – Walkthrough 4-Ans
What is the expected output?
int i=3,k=25;
double x = 0.2;
while ( k/i > 0){
x=x+0.3;
k=k-4;
i=i+x-1;
printf(“The current value of k/i is: %d \n”, k/i);
}
}






The current value of
The current value of
The current value of
The current value of
The current value of
The current value of
k/i is: 10
k/i is: 17
k/i is: 13
k/i is: 9
k/i is: 5
k/i is: 0
Validating Ranges Question 6-2
-
Robin Hood Summer Camps swimming
instructors must be at least 15 years old and not
more than 39 years old. Finish the code…
printf(“please enter the age”);
scanf(“%d”, &age);
while(
)
{
}
Do / while

Do-While Statement (Post-test Loop)

Often want to execute the statement(s) before testing the
condition, even for the first time; i.e. the block of code in the
do-while loop is always executed unconditionally the first time
Often used for validating input
Do - While statement syntax:


do{
statement(s);
}while (condition); /* loop is repeated as long as condition is
true (i.e. until condition is false) */
Note: Semi-colon at end of while
Do /While
The difference is tht the do will be executed at least one time
k=1051;
do{
printf(“%d square: %d cube: %d\n”, k, k*k, k*k*k );
k = k + 2;
}while(k<100);
=========================================================
k=1051;
while(k<100){
printf(“%d square: %d cube: %d\n”, k, k*k, k*k*k );
k = k + 2;
}
==========================================================
In this case using “do” will print one line, but using while, no lines are printed.
Validate ranges with do/while
Validate with do/while …
do{
if(rate < 15.00 || rate > 22.00){
printf(“Error: pay rate is out of range!”);
printf(“please enter the hourly rate: ”);
scanf(“%lf”, &rate);
}while(rate < 15.00 || rate > 22.00);
Validating A List of Values
Campers at Robin Hood receive a swimming grade
of A, B,or, C. All other codes are incorrect. This
is handled with an AND and != .
printf(‘Enter grade: ‘);
scanf( “ %c”, &grade);
while(grade != ‘A’ && grade != ‘B’ && grade != ‘C’ )
{
}
printf(“Error: Grade must be A, B, or, C !\n”
printf(‘Enter grade: ‘);
scanf( “ %c”, &grade);
Validating Input matches a value in a list
of values: Question 6-3
Apples are graded as ‘A’, ‘J’, or, ‘X’
printf(“Enter grade: “);
scanf(“ %c”, &grade);
while(
{
}
)
Compound Conditions
Prog Question 6-3-Ans
char categ;
printf(“Enter the apples category: “);
scanf(“% c”, &categ);
if (categ != ‘A’ && categ != ‘J’ && categ != ‘X’){
printf(“Error: Category must be A, J, or, X!\n”);
printf(“Enter the apples category: “);
scanf(“%d”, &categ);
}