IPC144 - LOOPS while - do while - for. Review - SWITCH The switch statement can also be used to...

27
IPC144 - LOOPS IPC144 - LOOPS while - do while - while - do while - for for

Transcript of IPC144 - LOOPS while - do while - for. Review - SWITCH The switch statement can also be used to...

Page 1: 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.

IPC144 - LOOPSIPC144 - LOOPS

while - do while - forwhile - do while - for

Page 2: 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.

Review - SWITCHReview - SWITCH

The switch statement can also be used to The switch statement can also be used to select code to be executed and code to select code to be executed and code to be skipped. It does not handle ranges. It be skipped. It does not handle ranges. It does not loop.does not loop.

switch ( expression )switch ( expression ) /* expression must be integer or single /* expression must be integer or single character */character */

{{

case (constant): statement(s); break;case (constant): statement(s); break;

case (constant): statement(s); break;case (constant): statement(s); break;

default: statement(s); /* optional */default: statement(s); /* optional */

}}

Page 3: 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.

SWITCH used in Banking SWITCH used in Banking PgmPgm

Consider the situation of opening a new Consider the situation of opening a new bank accountbank account..

char account_type;char account_type;printf(“ Type of account? c … chequing\n”);printf(“ Type of account? c … chequing\n”);printf(“ s … savings\n”);printf(“ s … savings\n”);scanf(“ %c”, &account_type);scanf(“ %c”, &account_type);switch (account_type)switch (account_type){{

case ‘c’: int_rate = 0.005; gift = 50.00; break;case ‘c’: int_rate = 0.005; gift = 50.00; break;case ‘s’: int_rate = 0.025; gift = 100.00; break;case ‘s’: int_rate = 0.025; gift = 100.00; break; default: int_rate = 0.0; gift = 50.00;default: int_rate = 0.0; gift = 50.00;

}}

Page 4: 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.

SWITCH – Two cases with SWITCH – Two cases with the same outcome -the same outcome -

We can join cases together if the code block is the We can join cases together if the code block is the samesame. .

Notice that case ‘c’ chequing and case ‘s’ saving have Notice that case ‘c’ chequing and case ‘s’ saving have identical code blocks because there is no break identical code blocks because there is no break statement.statement.

The switch statement could be written as:The switch statement could be written as:

switch (account_type)switch (account_type){{

case ‘c’:case ‘c’:case ‘s’:case ‘s’:

int_rate = 0.005;int_rate = 0.005;gift = 50.00;gift = 50.00;

break;break;default:default:

int_rate = 0.0;int_rate = 0.0;gift = 25.00;gift = 25.00;

}}

Page 5: 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.

switch – Prog Question 6-switch – Prog Question 6-44

Use the switch statement to Use the switch statement to program the following:program the following:

SmartKeySystems wants to SmartKeySystems wants to hire a Systems Analyst. They hire a Systems Analyst. They give each resume received a give each resume received a value from 1.5 to 3.5 for value from 1.5 to 3.5 for education and another value education and another value (1.5-3.5) for work (1.5-3.5) for work experience. The numbers experience. The numbers are added to get a total are added to get a total score. The score is rounded score. The score is rounded to the nearest integer. Here to the nearest integer. Here is what they do:is what they do:

Note: switch cannot be used Note: switch cannot be used for doubles – only int or for doubles – only int or char!char!

33 NothingNothing

4-54-5 Keep the Keep the resume resume on fileon file

66 Send a Send a thank you thank you letterletter

77 Schedule Schedule an an interviewinterview

Page 6: 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.

switch Prog Ques 4 –ansswitch Prog Ques 4 –ans #include<stdio.h>#include<stdio.h> main()main() {{ double total,educ,work;double total,educ,work; int i;int i; printf("Enter the score for education: "); scanf("%lf",&educ);printf("Enter the score for education: "); scanf("%lf",&educ); printf("Enter the score for work experience: "); scanf("%lf",&work);printf("Enter the score for work experience: "); scanf("%lf",&work); total = educ+work;total = educ+work; total = total + .5; /* prepare to round */total = total + .5; /* prepare to round */ i = total;i = total; switch (i)switch (i) {{ case 3: printf("Do not send a response\n"; break;case 3: printf("Do not send a response\n"; break; case 4:case 4: case 5: printf("Keep on file\n"; break;case 5: printf("Keep on file\n"; break; case 6: printf("Send a thank you letter\n", break;case 6: printf("Send a thank you letter\n", break; case 7: printf("Schedule Interview\n"); break;case 7: printf("Schedule Interview\n"); break; default:default: }} }}

Page 7: 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.

Summary of steps taken by Summary of steps taken by the switch statement.the switch statement.

1) 1) evaluate the expression. evaluate the expression. 2) 2) search to find matching case.search to find matching case. 3) 3) if a match is found, execute the instructions if a match is found, execute the instructions

until…until… - a break statement is reached- a break statement is reached - or a default statement is reached- or a default statement is reached - or a } brace ending the switch statement is reached.- or a } brace ending the switch statement is reached. At that point go to the statement following the switch statement.At that point go to the statement following the switch statement.

4) 4) If there is no match and there is a default code If there is no match and there is a default code block, block, perform the default code block.perform the default code block.

5) 5) if there is no match and there is no default code if there is no match and there is no default code block, exit block, exit the switch statement and continue the switch statement and continue program execution with program execution with the first statement the first statement following the switch statement.following the switch statement.

Page 8: 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.

Comments on switchComments on switch

Notes:Notes:1) 1) The default section is optional.The default section is optional.2) 2) break is needed to prevent one case from running break is needed to prevent one case from running into an other.into an other.3) 3) no code whatsoever will be performed if the is no no code whatsoever will be performed if the is no match and there is no match and there is no default section.default section.

4)4)Discussion Question:Discussion Question:Is switch preferable to an if - else if - else if - Is switch preferable to an if - else if - else if -

else?else? Readability: Switch / Case is usually better.Readability: Switch / Case is usually better. Speed: Switch is faster.Speed: Switch is faster. Flexibility: If / Else / Else If using ANDs/ ORs is Flexibility: If / Else / Else If using ANDs/ ORs is

usually better.usually better.

Page 9: 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.

Walkthrough 7-1Walkthrough 7-1

What is the expected output of the What is the expected output of the following pgm?following pgm?

int x=5; y=10; z=15;int x=5; y=10; z=15;

switch (z){switch (z){

case 2: printf(“case 2 is executing\n”); breakcase 2: printf(“case 2 is executing\n”); break

case 4: printf(“case 4 is executing\n”); case 4: printf(“case 4 is executing\n”);

case 5: printf(“case 5 is executing\n”); break;case 5: printf(“case 5 is executing\n”); break;

default: printf(“The default is executing\n”);default: printf(“The default is executing\n”);

}}

Page 10: 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.

Walkthrough 7-2Walkthrough 7-2

What is the expected output of the What is the expected output of the following pgm?following pgm?

int x=5; y=10; z=15;int x=5; y=10; z=15;

switch (y/x){switch (y/x){

case 2: printf(“case 2 is executing\n”); break;case 2: printf(“case 2 is executing\n”); break;

case 4: printf(“case 4 is executing\n”); case 4: printf(“case 4 is executing\n”);

case 5: printf(“case 5 is executing\n”); break;case 5: printf(“case 5 is executing\n”); break;

default: printf(“The default is executing\n”);default: printf(“The default is executing\n”);

}}

Page 11: 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.

Walkthrough 7-3Walkthrough 7-3

What is the expected output of the What is the expected output of the following pgm?following pgm?

int x=5; y=10; z=15;int x=5; y=10; z=15;

switch (x-1){switch (x-1){

case 2: printf(“case 2 is executing\n”); break;case 2: printf(“case 2 is executing\n”); break;

case 4: printf(“case 4 is executing\n”); case 4: printf(“case 4 is executing\n”);

case 5: printf(“case 5 is executing\n”); break;case 5: printf(“case 5 is executing\n”); break;

default: printf(“The default is executing\n”);default: printf(“The default is executing\n”);

}}

Page 12: 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.

Prog Question 7-5Prog Question 7-5

The cost of 10 corn depends on the month. The cost of 10 corn depends on the month.

In July (month 7) it is $3.75In July (month 7) it is $3.75

In August (month 8) it is $4.25In August (month 8) it is $4.25

The user enters the month number.The user enters the month number.

We can can use switch or if.We can can use switch or if.

Which one is better?Which one is better?

Page 13: 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.

Prog Question 7-5- AnsProg Question 7-5- Ans

Switch is better because it will run faster. Switch is better because it will run faster. In a simple case like this, it is very readable.In a simple case like this, it is very readable.

printf(“Enter the month number:”);printf(“Enter the month number:”);scanf(“%d”, &month);scanf(“%d”, &month);

switch (month){switch (month){ case 7: price = 3.75; break;case 7: price = 3.75; break; case 8: price = 4.25;case 8: price = 4.25;

}}

Page 14: 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.

Prog Question 7-6Prog Question 7-6

The cost of 10 corn The cost of 10 corn depends on the depends on the month and the grade.month and the grade.

Use a switch to select Use a switch to select the correct month the correct month and within each case, and within each case, use an if to select the use an if to select the right price.right price.

The user enters the The user enters the month number and month number and the grade number.the grade number.

MonthMonth

NumbNumberer

Grade Grade AA

=1=1

Grade Grade BB

=2=2

7 7

(July)(July)$3.50$3.50 $2.85$2.85

88

(Augus(August)t)

$4.00$4.00 $3.05$3.05

Page 15: 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.

Prog Question 7-6 - AnsProg Question 7-6 - Ansprintf(“Enter the month and grade numbers separated by a space:”);printf(“Enter the month and grade numbers separated by a space:”);scanf(“%d %d”, &month, &grade);scanf(“%d %d”, &month, &grade);

switch (month){switch (month){ case 7: case 7:

if (grade == 1)if (grade == 1)price = 3.50;price = 3.50;

else else price = 2.85;price = 2.85;

break;break;

case 8: case 8: if (grade == 1)if (grade == 1)

price = 4.00;price = 4.00; else else

price = 3.05;price = 3.05;}}

Page 16: 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.

WhileWhile

To perform some code repeatedlyTo perform some code repeatedlyWrite a program to print odd numbers between 50 and 100.Write a program to print odd numbers between 50 and 100.

The program prints the number, the square of the number The program prints the number, the square of the number and the cube of the number.and the cube of the number.

k=51;k=51;

while(k<100){while(k<100){

printf(“%d square: %d cube: %d\n”, k, k*k, k*k*k );printf(“%d square: %d cube: %d\n”, k, k*k, k*k*k );

k = k + 2;k = k + 2;

}}

printf (“ All done\n”);printf (“ All done\n”);

Page 17: 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.

Prog 7-7 – Pie EatingProg 7-7 – Pie Eating

While – Perform statements While – Perform statements repeatedlyrepeatedly

A person is practicing for a pie-eating A person is practicing for a pie-eating contest. They start with a pie of 750 contest. They start with a pie of 750 grams. Each day they eat 10% more grams. Each day they eat 10% more than the previous day.than the previous day.

How many days will it take to get to How many days will it take to get to the goal of 2 kilograms?the goal of 2 kilograms?

Page 18: 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.

Prog 7-7 – Pie Eating - Prog 7-7 – Pie Eating - AnsAns

While – Perform statements repeatedlyWhile – Perform statements repeatedly

#include<stdio.h>#include<stdio.h> main()main(){{ int days = 0;int days = 0; double grams = 750;double grams = 750; while(grams < 2000){while(grams < 2000){ grams = grams * 1.1; /* to add 10 % */grams = grams * 1.1; /* to add 10 % */ days = days + 1;days = days + 1; printf("On day %d you ate %.2lf grams\printf("On day %d you ate %.2lf grams\

n",days+1,grams);n",days+1,grams); }} printf("It took you %d days to get to your goal\n", days+1);printf("It took you %d days to get to your goal\n", days+1);}}

Page 19: 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.

While – Walkthrough 4While – Walkthrough 4

What is the expected output?What is the expected output?

int i=3,k=25;int i=3,k=25;double x = 0.2;double x = 0.2;while ( k/i > 0){while ( k/i > 0){

x=x+0.3;x=x+0.3;k=k-4;k=k-4;i=i+x-1;i=i+x-1;printf(“The current value of k/i is: %d \n”, printf(“The current value of k/i is: %d \n”,

k/i);k/i);}}

}}

Page 20: 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.

While – Walkthrough 4-While – Walkthrough 4-AnsAns

What is the expected output?What is the expected output?

int i=3,k=25;int i=3,k=25;double x = 0.2;double x = 0.2;while ( k/i > 0){while ( k/i > 0){

x=x+0.3;x=x+0.3;k=k-4;k=k-4;i=i+x-1;i=i+x-1;printf(“The current value of k/i is: %d \n”, k/i);printf(“The current value of k/i is: %d \n”, k/i);

}}}}

The current value of k/i is: 10 The current value of k/i is: 10 The current value of k/i is: 17 The current value of k/i is: 17 The current value of k/i is: 13 The current value of k/i is: 13 The current value of k/i is: 9 The current value of k/i is: 9 The current value of k/i is: 5 The current value of k/i is: 5 The current value of k/i is: 0 The current value of k/i is: 0

Page 21: 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.

Validating Ranges Question 6-Validating Ranges Question 6-22

- Robin Hood Summer Camps Robin Hood Summer Camps swimming instructors must be at least swimming instructors must be at least 15 years old and not more than 39 15 years old and not more than 39 years old. Finish the code…years old. Finish the code…

printf(“please enter the age”);printf(“please enter the age”);scanf(“%d”, &age);scanf(“%d”, &age);while(while( ))

{{

}}

Page 22: 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.

Do / whileDo / while

Do-While Statement (Post-test Loop) Do-While Statement (Post-test Loop) Often want to execute the statement(s) before Often want to execute the statement(s) before

testing the condition, even for the first time; i.e. testing the condition, even for the first time; i.e. the block of code in the do-while loop is always the block of code in the do-while loop is always executed unconditionally the first timeexecuted unconditionally the first time

Often used for validating inputOften used for validating input Do - While statement syntax:Do - While statement syntax:

do{do{statement(s); statement(s);

}while (condition); /* loop is repeated as long as condition is }while (condition); /* loop is repeated as long as condition is true (i.e. until condition is false) */true (i.e. until condition is false) */

Note: Semi-colon at end of whileNote: Semi-colon at end of while

Page 23: 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.

Do /WhileDo /While

The difference is tht the do will be executed at The difference is tht the do will be executed at least one timeleast one time

k=1051;k=1051;

do{do{

printf(“%d square: %d cube: %d\n”, k, k*k, k*k*k );printf(“%d square: %d cube: %d\n”, k, k*k, k*k*k );

k = k + 2;k = k + 2;

}while(k<100);}while(k<100);

==================================================================================================================

k=1051;k=1051;

while(k<100){while(k<100){

printf(“%d square: %d cube: %d\n”, k, k*k, k*k*k );printf(“%d square: %d cube: %d\n”, k, k*k, k*k*k );

k = k + 2;k = k + 2;

}}

====================================================================================================================

In this case using “do” will print one line, but using while, no lines In this case using “do” will print one line, but using while, no lines are printed.are printed.

Page 24: 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.

Validate ranges with Validate ranges with do/whiledo/while

Validate with do/while …Validate with do/while …do{do{

if(rate < 15.00 || rate > 22.00){if(rate < 15.00 || rate > 22.00){

printf(“Error: pay rate is out of printf(“Error: pay rate is out of range!”);range!”);

printf(“please enter the hourly rate: ”);printf(“please enter the hourly rate: ”);scanf(“%lf”, &rate);scanf(“%lf”, &rate);

}while(rate < 15.00 || rate > 22.00);}while(rate < 15.00 || rate > 22.00);

Page 25: 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.

Validating A List of Validating A List of ValuesValues

Campers at Robin Hood receive a Campers at Robin Hood receive a swimming grade of A, B,or, C. All other swimming grade of A, B,or, C. All other codes are incorrect. This is handled codes are incorrect. This is handled with an AND and != .with an AND and != .

printf(‘Enter grade: ‘);printf(‘Enter grade: ‘); scanf( “ %c”, &grade); scanf( “ %c”, &grade); while(grade != ‘A’ && grade != ‘B’ && grade != ‘C’ )while(grade != ‘A’ && grade != ‘B’ && grade != ‘C’ )

{{ printf(“Error: Grade must be A, B, or, C !\n”printf(“Error: Grade must be A, B, or, C !\n”printf(‘Enter grade: ‘);printf(‘Enter grade: ‘);scanf( “ %c”, &grade);scanf( “ %c”, &grade);

}}

Page 26: 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.

Validating Input matches a Validating Input matches a value in a list of values: value in a list of values:

Question 6-3Question 6-3Apples are graded as ‘A’, ‘J’, or, ‘X’Apples are graded as ‘A’, ‘J’, or, ‘X’

printf(“Enter grade: “);printf(“Enter grade: “);

scanf(“ %c”, &grade); scanf(“ %c”, &grade);

while( )while( )

{{

}}

Page 27: 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.

Compound ConditionsCompound ConditionsProg Question 6-3-AnsProg Question 6-3-Ans

char categ;char categ;

printf(“Enter the apples category: “);printf(“Enter the apples category: “);

scanf(“% c”, &categ);scanf(“% c”, &categ);

if (categ != ‘A’ && categ != ‘J’ && categ != ‘X’){if (categ != ‘A’ && categ != ‘J’ && categ != ‘X’){

printf(“Error: Category must be A, J, or, X!\n”);printf(“Error: Category must be A, J, or, X!\n”);

printf(“Enter the apples category: “);printf(“Enter the apples category: “);

scanf(“%d”, &categ);scanf(“%d”, &categ);

}}