34
1 C Programming for Engineers Iteration ICEN 360– Spring 2017 Prof. Dola Saha

C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

Embed Size (px)

Citation preview

Page 1: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

1

C Programming for Engineers

IterationICEN 360– Spring 2017Prof. Dola Saha

Page 2: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

2

Data type conversions

Ø Grade average example§ 𝑐𝑙𝑎𝑠𝑠𝑎𝑣𝑒𝑟𝑎𝑔𝑒 = ∑ ,-./0�

�23450-67893/0298

§ Grade and number of students can be integers§ Averages do not always evaluate to integer values, needs to be floating

point for accuracy.§ The result of the calculation total / counter is an integer

because total and counter are both integer variables.

Page 3: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

3

Explicit conversionsØ Dividing two integers results in integer division in which any

fractional part of the calculation is truncated (i.e., lost).Ø To produce a floating-point calculation with integer values, we

create temporary values that are floating-point numbers.Ø C provides the unary cast operator to accomplish this task.§ average = ( float ) total / counter;

Ø includes the cast operator (float), which creates a temporary floating-point copy of its operand, total.

Ø Using a cast operator in this manner is called explicit conversion.Ø The calculation now consists of a floating-point value (the

temporary float version of total) divided by the unsigned intvalue stored in counter.

Page 4: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

4

Implicit conversionØ C evaluates arithmetic expressions only in which the data

types of the operands are identical.Ø To ensure that the operands are of the same type, the

compiler performs an operation called implicit conversion on selected operands.

Ø For example, in an expression containing the data types unsigned int and float, copies of unsigned intoperands are made and converted to float.

Ø In our example, after a copy of counter is made and converted to float, the calculation is performed and the result of the floating-point division is assigned to average.

Page 5: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

5

Assignment operatorsØ C provides several assignment operators for abbreviating

assignment expressions.Ø For example, the statement

o c = c + 3;Ø can be abbreviated with the addition assignment

operator += aso c += 3;

Ø The += operator § adds the value of the expression on the right of the operator to the

value of the variable on the left of the operator § and stores the result in the variable on the left of the operator.

Page 6: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

6

Comparison of Prefix & Postfix Increments

Page 7: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

7

Assignment operators

Ø Any statement of the formo variable = variable operator expression;

Ø where operator is one of the binary operators +, -, *, /or % (or others we’ll discuss in Chapter 10), can be written in the form o variable operator= expression;

Ø Thus the assignment c += 3 adds 3 to c.

Page 8: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

8

Assignment operator - examples

Page 9: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

9

Unary Increment & Decrement Operators

Page 10: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

10

Increment Example

Page 11: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

11

Increment Example

Output

Page 12: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

12

Precedence

Page 13: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

13

for Iteration Statement - Syntaxfor (initialization expression;

loop repetition condition;update expression)

statement;

for (count_star = 0;count_star < N;count_star ++)

printf(“*”);

Page 14: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

14

for Iteration Statement - Syntax

Ø The general format of the for statement is for (initialization; condition; update expression) {

statement}

where § the initialization expression initializes the loop-control variable (and

might define it), § the condition expression is the loop-continuation condition and § the update expression increments the control variable.

Page 15: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

15

for Iteration Statement

Ø Counter-controlled iteration

Page 16: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

16

Flow chart

Page 17: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

17

for Iteration Statement – Common Error

Off-By-One ErrorsØ Notice that program uses the loop-continuation condition

counter <= 10.Ø If you incorrectly wrote counter < 10, then the loop

would be executed only 9 times.Ø This is a common logic error called an off-by-one error.

Page 18: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

18

for Iteration Statement – Common Practice

Ø Start the loop from 0

for (i=0; i<10; i++)printf(“It will be printed 10 times.\n”);

for (i=1; i<=10; i++)printf(“It will be printed 10 times.\n”);

Page 19: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

19

Optional Header in for Statement

Ø The three expressions in the for statement are optional.

Ø If the condition expression is omitted, C assumes that the condition is true, thus creating an infinite loop.

Ø You may omit the initialization expression if the control variable is initialized elsewhere in the program.

Ø The increment may be omitted if it’s calculated by statements in the body of the for statement or if no increment is needed.

Page 20: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

20

Valid code snippets

for (;;) printf(“The code is in infinite loop\n”);

int i=0;for (; i<10; i++)

printf(“It will be printed 10 times.\n”);

int i=0;for (; i<10; ){

printf(“It will be printed 10 times.\n”);i++;

}

Page 21: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

21

Examples of varying control variableTaskVary the control variable from 1 to 100 in increments of 1.

Vary the control variable from 100 to 1 in increments of -1 (decrements of 1).

Vary the control variable from 7 to 77 in steps of 7.

Vary the control variable from 20 to 2 in steps of -2.

Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17.

Vary the control variable over the following sequence of values: 44, 33, 22, 11, 0.

Page 22: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

22

Examples of varying control variableTask for LoopVary the control variable from 1 to 100 in increments of 1.

for (i = 1; i <= 100; ++ i)

Vary the control variable from 100 to 1 in increments of -1 (decrements of 1).

for (i = 100; i >= 1; --i)

Vary the control variable from 7 to 77 in steps of 7.

for (i = 7; i <= 77; i += 7)

Vary the control variable from 20 to 2 in steps of -2.

for (i = 20; i >= 2; i -= 2)

Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17.

for (j = 2; j <= 17; j += 3)

Vary the control variable over the following sequence of values: 44, 33, 22, 11, 0.

for (j = 44; j >= 0; j -= 11)

Page 23: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

23

For Statement NotesØ The initialization, loop-continuation condition and update expression

can contain arithmetic expressions.

Ø For example, if x = 2 and y = 10, the statementfor (j = x; j <= 4 * x * y; j += y / x)

is equivalent to the statementfor (j = 2; j <= 80; j += 5)

Ø If the loop-continuation condition is initially false, the loop body does not execute.

Page 24: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

24

Nested for Loopint row, col;for (row=0; row<2; row++)

for (col=0; col<3; col++)printf(“%d, %d\n”, row, col);

Page 25: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

25

Nested for Loopint row, col;for (row=0; row<2; row++)

for (col=0; col<3; col++)printf(“%d, %d\n”, row, col);

0, 00, 10, 21, 01, 11, 2

Sample Output

Page 26: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

26

Application: Summing even numbers

Page 27: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

27

Application: Compound Interest CalculationØ Consider the following problem statement: § A person invests $1000.00 in a savings account yielding 5% interest. Assuming that

all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts:

a = p(1 + r)n

wherep is the original amount invested (i.e., the principal)r is the annual interest raten is the number of yearsa is the amount on deposit at the end of the nth year.

Page 28: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

28

C Code for Compound Interest Calculation

Page 29: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

29

Output

Page 30: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

30

Classwork Assignment

Ø Write a program that finds the smallest of several integers. Assume that the first value read specifies the number of values remaining. Your program should read only one value each time scanf is executed.

Ø A typical input sequence might be § 5 400 500 300 200 100 § where 5 indicates that the subsequent five values are to be used for

finding minimum.

Page 31: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

31

Classwork Assignment

Ø Write a program that prints the following patterns separately, one below the other. Use for loops to generate the patterns. [Hint: The last two patterns require that each line begin with an appropriate number of blanks.]

Exercises 153

4.13 (Calculating the Product of Odd Integers) Write a program that calculates and prints theproduct of the odd integers from 1 to 15.

4.14 (Factorials) The factorial function is used frequently in probability problems. The factorial ofa positive integer n (written n! and pronounced “n factorial”) is equal to the product of the positiveintegers from 1 to n. Write a program that evaluates the factorials of the integers from 1 to 5. Print theresults in tabular format. What difficulty might prevent you from calculating the factorial of 20?

4.15 (Modified Compound-Interest Program) Modify the compound-interest program ofSection 4.6 to repeat its steps for interest rates of 5%, 6%, 7%, 8%, 9%, and 10%. Use a for loopto vary the interest rate.

4.16 (Triangle-Printing Program) Write a program that prints the following patterns separately,one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by asingle printf statement of the form printf( "%s", "*" ); (this causes the asterisks to print side byside). [Hint: The last two patterns require that each line begin with an appropriate number of blanks.]

4.17 (Calculating Credit Limits) Collecting money becomes increasingly difficult during peri-ods of recession, so companies may tighten their credit limits to prevent their accounts receivable(money owed to them) from becoming too large. In response to a prolonged recession, one companyhas cut its customers’ credit limits in half. Thus, if a particular customer had a credit limit of $2000,it’s now $1000. If a customer had a credit limit of $5000, it’s now $2500. Write a program thatanalyzes the credit status of three customers of this company. For each customer you’re given:

a) The customer’s account numberb) The customer’s credit limit before the recessionc) The customer’s current balance (i.e., the amount the customer owes the company).

Your program should calculate and print the new credit limit for each customer and shoulddetermine (and print) which customers have current balances that exceed their new credit limits.

4.18 (Bar Chart Printing Program) One interesting application of computers is drawing graphsand bar charts (sometimes called “histograms”). Write a program that reads five numbers (each be-tween 1 and 30). For each number read, your program should print a line containing that numberof adjacent asterisks. For example, if your program reads the number seven, it should print *******.

4.19 (Calculating Sales) An online retailer sells five different products whose retail prices areshown in the following table:

(A) (B) (C) (D)* ********** ********** *** ********* ********* ***** ******** ******** ******* ******* ******* ********* ****** ****** *********** ***** ***** ************* **** **** *************** *** *** ***************** ** ** ******************* * * **********

Product number Retail price

1 $ 2.982 $ 4.503 $ 9.984 $ 4.495 $ 6.87

Page 32: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

32

do ... while Iteration Statement

Ø Similar to the while statement.Ø do

statementwhile (condition);

Ø The loop-continuation condition after the loop body is performed.

Ø The loop body will be executed at least once.

Ø while (condition)

Ø The loop-continuation condition is tested at the beginning of the loop

Page 33: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

33

Example do ... while Iteration Statement

Page 34: C Programming for Engineers Iteration · ... The factorial function is used frequently in probability problems. The factorial of ... so companies may tighten their credit limits to

34

Flowchart do ... while Iteration Statement