21
IPC144 - LOOPS IPC144 - LOOPS while - do while - while - do while - for for

IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Embed Size (px)

Citation preview

Page 1: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

IPC144 - LOOPSIPC144 - LOOPS

while - do while - forwhile - do while - for

Page 2: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Assignment 1Assignment 1

Let’s talk …Let’s talk …

Page 3: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

WhileWhile

To perform some code repeatedlyTo perform some code repeatedly

Write a program to print odd numbers between 50 Write a program to print odd numbers between 50 and 100.and 100.

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

k=51;k=51;

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

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

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

}}

Page 4: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Do / whileDo / whileDo-While Statement is similar to while but the test is at the Do-While Statement is similar to while but the test is at the

bottom of the loop) bottom of the loop) So the statement(s) are always performed once at least. So the statement(s) are always performed once at least.

k=51;k=51;do{do{

printf(“%d square: %d \n”, k, k*k );printf(“%d square: %d \n”, k, k*k );k = k + 2;k = k + 2;

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

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

Page 5: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Compare While with Do /WhileCompare While with Do /While

Using do the body will be executed at least one Using do the body will be executed at least one timetime

But with while But with while the body can be executedthe body can be executed zero times zero times

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.

k=1051;k=1051;do{do{

printf(“%d square: %d \n”, k, k*k);printf(“%d square: %d \n”, 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 \n”, k, k*k, );printf(“%d square: %d \n”, k, k*k, );k = k + 2;k = k + 2;

}}==================================================================================

Page 6: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

forfor

The For Statement allows the programmer to The For Statement allows the programmer to specify in a single line:specify in a single line:

1) the starting value of the loop variable 1) the starting value of the loop variable (initialization)(initialization)

2) the test 2) the test

3) The change in value of the loop variable (often 3) The change in value of the loop variable (often called the step). called the step).

for (k=51; k<100; k=k+2){for (k=51; k<100; k=k+2){

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

}}

Page 7: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

forfor

Comments on the For Statement:Comments on the For Statement:

The test is performed The test is performed beforebefore entering the body of the entering the body of the loop.loop.

So the body can be executed zero times (similar to while) So the body can be executed zero times (similar to while) Here is an example:Here is an example:

j = 42; j = 42; for (k=51 ; k<j ; k=k+2){for (k=51 ; k<j ; k=k+2){

printf(“k is: %d and j is: %d . k is less than j\n”, k, printf(“k is: %d and j is: %d . k is less than j\n”, k, j );j );}}

Page 8: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

forforComments on the For Statement:Comments on the For Statement:

The The order of operationsorder of operations is: is:1) Set the loop variable to it’s starting value 1) Set the loop variable to it’s starting value 2) Perform the test2) Perform the test3) Perform the body of the loop if the test resolves to true 3) Perform the body of the loop if the test resolves to true 4) After the body has been performed, change the value of 4) After the body has been performed, change the value of

the loop variable as specified in the third part of the For.the loop variable as specified in the third part of the For.

j = 82; j = 82; for (k=51 ; k<j ; k=k+2){for (k=51 ; k<j ; k=k+2){

printf(“k is: %d and j is: %d . k is less than j\n”, k, printf(“k is: %d and j is: %d . k is less than j\n”, k, j );j );}}

Page 9: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

forforComments on the For Statement:Comments on the For Statement:

It’s unusual but the test does not have to be on the loop It’s unusual but the test does not have to be on the loop variable.variable.

printf(“Enter age: “); printf(“Enter age: “); scanf(“%d”, &age); /* assume age less scanf(“%d”, &age); /* assume age less

than 65 /*than 65 /*for (k=51 ; age <=65 ; k=k+1){for (k=51 ; age <=65 ; k=k+1){

income = 42000 * (age / 65);income = 42000 * (age / 65);printf(“Age: %d Income is: %.2lf \n “, printf(“Age: %d Income is: %.2lf \n “,

age,income);age,income);}}

Page 10: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

forforComments on the For Statement:Comments on the For Statement:

C will not stop you from changing the value of the loop C will not stop you from changing the value of the loop variable in the body of the loop, but it is not recommended variable in the body of the loop, but it is not recommended as we are not expecting changes in the loop variable in the as we are not expecting changes in the loop variable in the body. This makes the program difficult to follow.body. This makes the program difficult to follow.

for (k=51 ; k < 65 ; k=k+1){for (k=51 ; k < 65 ; k=k+1){income = 42000 * (k/65);income = 42000 * (k/65);age = k;age = k;printf(“Age: %d Income is: %.2lf \n “, printf(“Age: %d Income is: %.2lf \n “,

age,income);age,income);k = k + k%2;k = k + k%2;

}}Note: The age code is not recommended !Note: The age code is not recommended !

Page 11: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Validate ranges with Validate ranges with do/whiledo/while

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

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

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!”);

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

Page 12: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Validate ranges with WhileValidate ranges with While

Validate with while …Validate with while …

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){

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);

}}

Page 13: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Validating A List of Values Validating A List of Values Using ANDUsing AND

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 14: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Validating Input Matches a Validating Input Matches a Value in a List: Question 6-3Value in a List: Question 6-3

Apples 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 15: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Prog Question 6-3-Ans Prog Question 6-3-Ans Using !=Using !=

char categ;char categ;

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

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

while (categ != ‘A’ && categ != ‘J’ && categ != ‘X’){while (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);

}}

Page 16: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

FunctionsFunctions

- Functions can be used to break a Functions can be used to break a large problem into smaller pieces. large problem into smaller pieces.

- main( ) calls functions, but a main( ) calls functions, but a function can call other functions as function can call other functions as well.well.

- Main( ) will pass information to the Main( ) will pass information to the function so that it can perform it’s function so that it can perform it’s part of the work.part of the work.

Page 17: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Example of a FunctionExample of a Functionmain()main(){{

int num, ans;int num, ans;printf(“Enter a number: ");printf(“Enter a number: ");

scanf("%d", &num);scanf("%d", &num); ans = fn_triple(num); /* the input to the function is num, ans = fn_triple(num); /* the input to the function is num,

and the answer will and the answer will be in ans */be in ans */ printf(" total is %d: “ans);printf(" total is %d: “ans);}}

double fn_triple(int number)double fn_triple(int number){{ int answer;int answer; answer = number * 3;answer = number * 3; return answer;return answer;}}/* note carefully how the function returns it’s answer to /* note carefully how the function returns it’s answer to

main() */main() */

Page 18: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Function that Triples a Function that Triples a ValueValue

Steps:Steps:1.1. main() gets a value for the number.main() gets a value for the number.2.2. Main “calls” the function and copies the Main “calls” the function and copies the

value of number into num.value of number into num.3.3. The Function triples num and puts the The Function triples num and puts the

answer into a local variable called answer into a local variable called answer.answer.

4.4. In the return statement, the value for In the return statement, the value for answer is placed into the function name.answer is placed into the function name.

5.5. main() then receives the value into ans.main() then receives the value into ans.

Page 19: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

FunctionsFunctions

- In the example that follows main( ) In the example that follows main( ) gets the values and then calls gets the values and then calls fn_total_charge to calculate the fn_total_charge to calculate the total.total.

Page 20: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Example of a FunctionExample of a Functionmain()main(){{

int num; double price, total; char grade = ‘A’;int num; double price, total; char grade = ‘A’;printf(“Enter the number of apples and the price: ");printf(“Enter the number of apples and the price: ");

scanf("%d %lf", &num, &price);scanf("%d %lf", &num, &price); total = fn_total_charge(num, price);total = fn_total_charge(num, price); printf("%d apples cost $%.2lf\n",num, total);printf("%d apples cost $%.2lf\n",num, total);}}

double fn_total_charge(int number_sold, double double fn_total_charge(int number_sold, double price_each)price_each)

{{ double total_cost, tax_rate = .13; /* local variables */double total_cost, tax_rate = .13; /* local variables */ total_cost = (number_sold * price_each) * (1 + total_cost = (number_sold * price_each) * (1 +

tax_rate);tax_rate); return total_cost;return total_cost;}}

Page 21: IPC144 - LOOPS while - do while - for. Assignment 1 Let’s talk …

Functions – Guidelines Functions – Guidelines and Rulesand Rules

1.1. Each small program (called a function) should handle one Each small program (called a function) should handle one task (or function)task (or function)

  2.2. When coding functions, we attempt to have 55 lines or When coding functions, we attempt to have 55 lines or

less so that the programmer can see the entire function on less so that the programmer can see the entire function on one printed page.one printed page.

  3.3. The main() program will control the sequence, selection, The main() program will control the sequence, selection,

and looping involving functions. This is done by and looping involving functions. This is done by "calling "calling the functions".the functions".

  4.4. When main() calls a function, main will usually tell the When main() calls a function, main will usually tell the

function what values to use for certain key variables. This function what values to use for certain key variables. This is known as "is known as "passing values or variable addresses"passing values or variable addresses"..

  5.5. The function "sees" only the passed values, variables The function "sees" only the passed values, variables

whose address has been passed, and any locally defined whose address has been passed, and any locally defined variables.variables.