123
1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: [email protected] web: www.cs.utsa.edu/~korkmaz CS 2073 Computer Programming w/Eng. Applications Ch 3

1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: [email protected] web: korkmaz

Embed Size (px)

Citation preview

Page 1: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

1

Control Structures and Data Files

Turgay Korkmaz

Office: SB 4.01.13 Phone: (210) 458-7346

Fax: (210) 458-4437 e-mail: [email protected]

web: www.cs.utsa.edu/~korkmaz

CS 2073Computer Programming

w/Eng. Applications Ch 3

Page 2: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

2

Lecture++;

Name Addr Content

Lecture 7

Page 3: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

3

3.1 Algorithm Development So far, we considered very simple

programs (read, compute, print) Top-down Design

Start from the big picture Use a process called divide-and-conquer Keep dividing the problem until steps are

detailed enough to convert to a program Refinement with Pseudo-code (English like

statements) and Flowchart (diagram, graph)

Page 4: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

4

Pseudo-code Notation and Flowchart Symbols

Page 5: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

5

Structured Programming

Sequence

Selection

Repetition

yesno

yes

no

Use simple control structures to organize the solution to a problem

Page 6: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

6

Sequence

Page 7: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

7

Selection

Page 8: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

8

Repetition

Page 9: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

9

Extras Evaluation of alternative solution

A problem can be solved in many different ways

Which is the best (e.g, faster, less memory req) Error condition

Do not trust user! Check the data. A=b/c; Be clear about specifications

Generation of Test Data Test each of the error conditions Program validation and verification Program walkthrough

Page 10: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

10

3.2 Conditional Expressions Selection and repetition structures use

conditions, so we will first discuss them A condition is an expression (e.g., x= a

> b) that can be evaluated to be TRUE (any value > 0) or FALSE (value of 0)

Conditional Expression is composed of expressions combined with relational and/or logical operators

Page 11: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

11

Relational Operators

== equality (x == 3) != non equality (y != 0) < less than (x < y) > greater than (y > 10) <= less than equal to (x <= 0) >= greater than equal to (x >= y)

!!! a==b vs. a=b !!!

Page 12: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

12

Examples

A < B fabs(denum) < 0.0001 D = b > c; if (D)

A=b+c; Mixing with arithmetic op

X+Y >= K/3

4

2

-0.01

?

6

4

2

1

10

A

B

denum

D

b

c

X

Y

K

Page 13: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

13

Logical Operators ! not !(x==0) && and (x>=0) && (x<=10) || or (x>0) || (x<0)

A B A && B A || B !A !BFalse False False False True True

False True False True True False

True False False True False True

True True True True False False

Page 14: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

14

Examples A<B && C>=5 A+B * 2 < 5 && 4>=A/2 A<B || C<B && A-2 < 10 A < B < C ???? A<B<C is not the same as

(A<B) && (B<C)

4

2

6

A

B

C

Page 15: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

15

Precedence for Arithmetic, Relational, and Logical Operators

Page 16: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

16

Exercise Assume that following variables are

declareda = 5.5 b = 1.5 k = -3

Are the following true or falsea < 10.0 + ka + b >= 6.5k != a-b!(a == 3*b)a<10 && a>5fabs(k)>3 || k<b-a

Page 17: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

17

Exercise: Logical Circuit

y1 = x1 && x2;y2 = x3 || x4;y3 = !x5;z1 = y1 || y2; z2 = y2 && y3Without using y1, y2, y3

z1 = x1 && x2 || (x3 || x4);z2 = (x3 || x4) && !x5;

ANDx1

x2

x3

x4

x5

y1

z2

z1

y3

y2

Write a program that reads x1, x2, x3, x4, x5 and computes/prints z1, z2

OR

NOT

OR

AND

Page 18: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

Exercise

18

a

bC

x

Page 19: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

19

Lecture++;

Name Addr Content

Lecture 8

Page 20: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

20

3.3 Selection Statements

if if else switch

Page 21: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

21

if statement if(Boolean expression)

statement; /* single statement */

if(Boolean expression) { /* more than one statement */

statement1;…

statement n; }

Page 22: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

22

if statement - examplesif (x > 0)

k++;

if(x > 0) {y = sqrt(x);k++;

}

if(x > 0) /* a common mistake */ y = sqrt(x);

k++;

Name Addr Content

x 9

y 5

k 4

Page 23: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

23

if else statement

if(Boolean expression)statement;

elsestatement;

if(Boolean expression) {statement block

} else {statement block

}

Page 24: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

24

if else statement What does the following program do? Assume that x, y, temp are declared.

if (x > y)

temp = x;

else

temp = y;

Name Addr Content

x 9

y 5

temp ?

if (x > y){ temp = x;

} else { temp = y;

}

Page 25: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

25

Exercise Write an if-else statement to find both the

maximum and minimum of two numbers. Assume that x, y, min, max are declared.

if (x > y) { max = x; min = y;} else { max = y; min = x;}

Name Addr Content

x 9

y 5

max ?

min ?

9595

3895

3883

6683

6666

Page 26: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

26

if else statement

if (x > y)

temp = x;

else

temp = y;

Split the following statement into two separate if statements

if (x > y)

temp = x;

if (x <= y)

temp = y;

Page 27: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

Flow chart for previous slide

27

x > y

temp=xtemp=y

T

if (x > y)

temp = x;

else

temp = y;

if (x > y)

temp = x;

if (x <= y)

temp = y;

x > y

temp=x

temp=y

T

x <= yT

Page 28: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

28

nested if-else

if(x > y)if(y < z)

k++;else

m++;else

j++;

x > y

y < z

k++m++

j++

T

T

F

F

if(x > y) {if(y < z) {

k++;} else {

m++;}

} else {j++;

}

Page 29: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

29

Exercise

x > y

y < z

k++m++

j++

T

T

F

F

int x=9, y=7, z=2, k=0, m=0, j=0;if(x > y)

if(y < z)k++;

elsem++;

elsej++;

What are the values of j, k and m?

Page 30: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

30

Exercise: Find the value of a

int a = 750;if (a>0) if (a >= 1000) a = 0; else if (a <500) a =a*2; else a =a*10;else a =a+3;

a > 0

a >= 1000

a = 0

a =a+3 a < 500

a =a*2a =a*10

T

T

T

Page 31: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

31

Exercise: Find the value of a

int a = 750;if (a>0) { if (a >= 1000) { a = 0; } else { if (a <500) { a =a*2; } else { a =a*10; } }} else { a =a*3;}

a > 0

a >= 1000

a = 0

a =a+3 a < 500

a=a*2a =a*10

T

T

T

Page 32: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

32

Indentation

int a = 750;if (a>0) if (a >= 1000) a = 0; else if (a <500) a=a*2; else a=a*10;else a =a+3;

int a = 750;if (a>0)if (a >= 1000)a = 0;elseif (a <500)a=a*2;elsea=a*10;elsea = a+3;

Not good

Good

Page 33: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

33

Indentation (cont’d) What is the output of the following

programs int a = 5, b = 3; if (a>10) {

a = 50;b = 20;}printf(" a = %d, b = %d\n",a, b);

if (a>10) a = 50; b = 20;

printf(" a = %d, b = %d\n",a, b);if (a>10) a = 50;b = 20;

printf(" a = %d, b = %d\n",a, b);

if (a>10) { a = 50; b = 20;}printf(" a = %d, b = %d\n",a, b);

Not good

Good

Page 34: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

34

Exercise: Region in a plane

Write a program that reads a point (x, y) from user and prints its region

Region 1

Region 4

Region 2

Region 3

For example

Enter x y: 3 -1

This point is in Region 4

Enter x y: -1 -5

This point is in region 3

Enter x y: 0 5 ???????

Page 35: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

35

Lecture++;

Name Addr Content

Lecture 9

Page 36: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

36

Switch Statementswitch(expression) {

case constant:statement(s);break;

case constant:statement(s);break;

default: /* default is optional */

statement(s);}

Page 37: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

37

Switch Statement Expression must be of type integer or character The keyword case must be followed by a constant break statement is required unless you want all

subsequent statements to be executed.

switch (op_code) {

case ‘N’: printf(“Normal\n”); break;

case ‘M’: printf(“Maintenance Needed\n”);

break; default: printf(“Error\n”); break; }

Page 38: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

38

Exercise Convert the switch statement into if statement.

switch (op_code) { case ‘N’: printf(“Normal\n”); break; case ‘M’: printf(“Maintenance Needed\n”); break; default: printf(“Error\n”); break;}

if (op_code == ‘N’) printf(“Normal\n”); else if (op_code == ‘M’) printf(“Maintenance Needed\n”);else printf(“Error\n”);

Page 39: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

39

Exercise

Convert the following nested if/else statements to a switch statement

if (rank==1 || rank==2) printf("Lower division \n");else{ if (rank==3 || rank==4) printf("Upper division \n"); else   {  if (rank==5) printf("Graduate student \n"); else printf("Invalid rank \n"); }}

switch(rank) {case 1:case 2: printf("Lower division \n"); break;

case 3:case 4: printf("Upper division \n"); break;case 5: printf("Graduate student \

n"); break;default: printf("Invalid rank \n");

}

Page 40: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

40

More selection examples

Page 41: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

41

Write if-else statement

score > 70

age > 18

Good jobExcellent job

age > 18

Very bad

You passYou fail

T

TT

Good luck next time

Don’t worry

Page 42: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

42

if (score > 70) {printf(“You Pass\n”);if (age > 18) {

printf(“Good job \n”);} else {

printf(“Excellent job\n”);}

} else {printf(“You Fail\n”);if (age > 18) {

printf(“ Very bad \n”);} else {

printf(“ Don’t worry \n”);}

printf(“ Good luck next time \n”);}

Page 43: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

43

get b, c from usera = b + c

a <= 10 and b-c > 6TF

F

Print “RIGTH-LEFT”, a, b, ca= 10 - c * c

c = a+bPrint “FINAL”, a, b, c

Print “LEFT-LEFT”, a, b, cb= a * -c

c != b

a*b<=12

Print “RIGTH”, a, b, cb= 5 + c * 2T

Print “LEFT-RIGTH”, a, b, cc= 5 + c * 2

F T

Print “RIGHT”, a, b, c meansprintf(“RIGHT a=%lf b=%lf c=%lf \n”,a, b, c);

Page 44: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

44

a=b+c; if (a<=10 && b-c>6) { printf("RIGHT a=%lf b=%lf c=%lf \n", a, b, c);

b=5+c*2; if (a*b<=12) {

} else { printf("RIGHT-LEFT a=%lf b=%lf c=%lf \n",a, b, c); a=10-c*c; }} else { if (c != b) { printf("LEFT-RIGHT a=%lf b=%lf c=%lf \n",a, b, c); c=5+c*2; } printf("LEFT-LEFT a=%lf b=%lf c=%lf \n",a, b, c); b=a*-c;}c=a+b;printf("Final a=%lf b=%lf c=%lf \n",a, b, c);

Page 45: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

45

Exercise: which task takes more time

Suppose we have two tasks A and B A takes Ah hours, Am minutes, and As

seconds B takes Bh hours, Bm minutes, and Bs

seconds User enters Ah Am As Bh Bm Bs Write if-else statements to print out

which task takes more time?

Page 46: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

46

Max, Min, Median Write a program that reads 3 numbers a, b

and c from user and computes minimum, median and maximum of the numbers.

Example: a = 2, b = 5, c = 3

minimum = 2, maximum = 5, median = 3 a = 2, b = 2, c = 3

minimum = 2, maximum = 3, median = 2

Page 47: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

47

Another if-else flowchart

if( A > 8) { A=b+c; if(A < 4) B=b*c; if(A > 8) B=b/c;} else { A=b-c; if(A < 5) B=b+c; else B=b%c; A=B; }

A > 8

A < 4

A > 8

B=b*c

B=b/c

A=b-c

A < 5

B=b+cB=b%c

A=B

A=b+c

T

TT

T

Page 48: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

48

Exercise: Assign Letter Grade Given a score and the following grading scale

write a program to find the corresponding grade.

90-100 A80-89 B70-79 C60-69 D

0-59 F

Page 49: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

49

Solution-1 if ((score >= 90) && (score <=100)) grade = 'A'; else if ((score >= 80) && (score <= 89)) grade = 'B'; else if ((score >= 70) && (score <= 79)) grade = 'C'; else if ((score >= 60) && (score <= 69)) grade = ‘D'; else if ((score >= 0) && (score <= 59)) grade = ‘F'; else printf("Invalide Score\n");

Page 50: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

50

Solution-2if ((score >= 0) && (score <= 100))

if (score >= 90) grade = 'A';

else if (score >= 80) grade = 'B';

else if (score >= 70) grade = 'C';

else if (score >= 60) grade = ‘D';

else grade = ‘F';

else printf("Invalide Score\n");

Page 51: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

51

Triangle inequality

Suppose we want to check if we can make a triangle using a, b, c

a

b

c

|a-b| <= c |a-c| <= b |b-c| <= a

a+b >= c a+c >= b b+c >= a

Page 52: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

52

Charge for money transfer

Suppose you transfer $N and bank’s charge occurs as follows.

Write a program that reads N and computes cost

Otherwise 30$10000 N1000 ifN of 1%.0$15

1000N500 if N of 2% $10500$ N if 10$

cos t

Page 53: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

53

Compute Queuing Delay

Write C program that computes and prints out average delay in a queuing system, where the average delay is given as follows

1 if

1 0 if )1()1(21

222

AvgDelay

Page 54: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

54

#include <stdio.h>int main(void){ /* Declare variables. If needed, you can declare more*/ double rho, mu, sigma, AvgDelay;

printf("Enter rho(utilization), mu(service time) and " "sigma (standard deviation of service time) : "); scanf("%lf %lf %lf", &rho, &mu, &sigma); /* Compute and print the average delay using rho, mu, sigma */ if( rho > 0 && rho < 1) { AvgDelay = (rho / (1 - rho)) – rho*rho / (2 * (1-rho)) * (1-mu*mu*sigma*sigma); printf("AvgDelay = %lf \n", AvgDelay); } else if (rho >=1){ printf("AvgDelay is infinity \n"); } else printf("rho cannot be negative \n"); system("pause"); /* Exit program. */ return 0;}

Page 55: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

55

Spell out a number in textusing if-else and switch

Write a program that reads a number between 1 and 999 from user and spells out it in English.

For example: 453 Four hundred fifty three 37 Thirty seven 204 Two hundred four

Page 56: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

56

Lecture++;

Name Addr Content

Lecture 10

Page 57: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

60

Loop (Repetition) Structures

Page 58: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

61

Problem: Conversion tabledegrees radians

Degrees to Radians

0 0.000000 10 0.174533 20 0.349066 30 0.523599

…340 5.934120

350 6.108653 360 6.283186

radians = degrees * PI / 180;

Page 59: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

62

#include <stdio.h>#define PI 3.141593

int main(void){ int degrees=0; double radians;

printf("Degrees to Radians \n"); degrees = 0; radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians);

degrees = 10; radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians);

degrees = 20; radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians);… degrees = 360; radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians);}

Sequential Solution

degrees = ??? radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians);

Not a good solution

Page 60: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

63

Loop Solution

degrees = ??? radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians);

#include <stdio.h>#define PI 3.141593

int main(void){ int degrees=0; double radians;

printf("Degrees to Radians \n"); while (degrees <= 360) {

radians = degrees*PI/180; printf("%6i %9.6f \n", degrees,

radians); degrees += 10; } }

degrees+=10means

degrees= degrees+10

Page 61: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

64

Loop (Repetition) Structures

while statement do while statement for statement Two new statements used with

loops break and continue

Page 62: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

65

while statement

while(expression)statement;

while(expression) { statement;statement;

…}

Page 63: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

66

Example#include <stdio.h>#define PI 3.141593

int main(void){ int degrees=0; double radians;

printf("Degrees to Radians \n"); while (degrees <= 360) { radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); degrees += 10; }return 0;}

Page 64: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

67

do while

dostatement;

while(expression);

do {statement1;statement2;

...} while(expression);

note - the expression is tested after the statement(s) are executed, so statements are executed at least once.

Page 65: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

68

Example#include <stdio.h>#define PI 3.141593

int main(void){ int degrees=0; double radians;

printf("Degrees to Radians \n"); do { radians = degrees*PI/180; printf("%6i %9.6f \n",degrees,radians); degrees += 10; } while (degrees <= 360); return 0;}

Page 66: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

69

for statement for(initialization ; test ; increment or decrement )

statement;

for(initialization ; test ; increment or decrement ){

statement;statement;

…}

Page 67: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

70

Example#include <stdio.h>#define PI 3.141593

int main(void){ int degrees; double radians;

printf("Degrees to Radians \n"); for (degrees=0; degrees<=360; degrees+=10) { radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); } return 0;}

Page 68: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

71

for statement

initializetest

Increment ordecrement

true

statement(s)statement(s)

Page 69: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

72

Examples

int sum =0, i;for( i=1 ; i < 7;i=i+2 ){

sum = sum+i;}

int fact=1, n;for( n=5 ; n>1 ; n--){

fact = fact * n;}

?

0

5

1

i

sum

n

fact

1

1

3

4

5

9

7

n--; means n=n-1;n++; means n=n+1;

Page 70: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

73

ExerciseDetermine the number of times that each of the following for loops are executed.

for (k=3; k<=10; k++) { statements;

}

for (k=3; k<=10; ++k) { statements;

}

for (count=-2; count<=5; count++) { statements;

}

1

increment

initialfinal

Page 71: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

74

Example What will be the output of the following program, also

show how values of variables change in the memory.int sum1, sum2, k;sum1 = 0;sum2 = 0;for( k = 1; k < 5; k++) { if( k % 2 == 0) sum1 =sum1 + k; else sum2 = sum2 + k;}printf(“sum1 is %d\n”, sum1);printf(“sum2 is %d\n”, sum2);

0 2 6

0 1 4

1 2 3 4 5

sum1

sum2

k

sum1 is 6sum2 is 4

Page 72: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

75

For vs. while loopConvert the following for loop to while loop

for( i=5; i<10; i++) { pritntf(“ i = %d \n”, i);

}

i=5;while(i<10){ pritntf(“ i = %d \n”, i); i++;

}

Page 73: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

76

break statement break;

terminates loop execution continues with the first statement

following the loop

sum = 0;for (k=1; k<=5; k++) {

scanf(“%lf”,&x); if (x > 10.0) break; sum +=x;}printf(“Sum = %f \n”,sum);

sum = 0;k=1;while (k<=5) {

scanf(“%lf”,&x); if (x > 10.0) break; sum +=x; k++;}printf(“Sum = %f \n”,sum);

Page 74: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

77

continue statement continue;

forces next iteration of the loop, skipping any remaining statements in the loop

sum = 0;for (k=1; k<=5; k++) {

scanf(“%lf”,&x); if (x > 10.0) continue; sum +=x;}printf(“Sum = %f \n”,sum);

sum = 0;k=1;while (k<=5) {

scanf(“%lf”,&x); if (x > 10.0) continue; sum +=x; k++;}printf(“Sum = %f \n”,sum);

sum = 0;k=1;while (k<=5) {

scanf(“%lf”,&x); if (x > 10.0){ k++; continue; } sum +=x; k++;}printf(“Sum = %f \n”,sum);

Page 75: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

78

Example: what will be the output

int main(){ int a, b, c; a=5; while(a > 2) { for (b = a ; b < 2 * a ; b++ ) { c = a + b; if (c < 8) continue; if (c > 11) break; printf( “a = %d b = %d c = %d \n”, a, b, c); } /* end of for-loop */ a--; } /* end of while loop */}

a = 5 b = 5 c = 10a = 5 b = 6 c = 11a = 4 b = 4 c = 8a = 4 b = 5 c = 9a = 4 b = 6 c = 10a = 4 b = 7 c = 11a = 3 b = 5 c = 8

Page 76: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

79

Example: A man walks Suppose a man (say, A)

stands at (0, 0) and waits for user to give him the direction and distance to go.

User may enter N E W S for north, east, west, south, and any value for distance.

When user enters 0 as direction, stop and print out the location where the man stopped

N

E

S

W

Page 77: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

80

float x=0, y=0; char direction; float distance; while (1) { printf("Please input the direction as N,S,E,W (0 to exit): "); scanf("%c", &direction); fflush(stdin); if (direction=='0'){ /*stop input, get out of the loop */ break; } if (direction!='N' && direction!='S' && direction!='E' && direction!='W') { printf("Invalid direction, re-enter \n"); continue; } printf("Please input the mile in %c direction: ", direction); scanf ("%f", &distance); fflush(stdin); if (direction == 'N'){ /*in north, compute the y*/ y = y + distance; } else if (direction == 'E'){ /*in east, compute the x*/ x = x + distance; } else if (direction == 'W'){ /*in west, compute the x*/ x= x - distance; } else if (direction == 'S'){ /*in south, compute the y*/ y = y- distance; } } printf("\nCurrent position of A: (%4.2f, %4.2f)\n", x, y); /* output A's location */

Page 78: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

81

Lecture++;

Name Addr Content

Lecture 13

Page 79: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

82

More loop examples

Page 80: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

83

Exercise

What is the output of the following program?for (i=1; i<=5; i++) { for (j=1; j<=4; j++){ printf(“*”);

} printf(“\n”);}

Output

********************

Page 81: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

84

Exercise What is the output of the

following program?

for (i=1; i<=5; i++) { for (j=1; j<=i; j++){ printf(“*”); } printf(“\n”);}

Output

***************

Page 82: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

What/how do you need to change in th following program?for (i=1; i<=5; i++) { for (j=1; j<=i; j++){ printf(“*”); } printf(“\n”);}

85

Example: nested loops to generate the following output

i=1 * i=2 + +i=3 * * * i=4 + + + +i=5 * * * * *

int i, j;for(i=1; i <= 5; i++){ printf("i=%d ", i); for(j=1; j <= i; j++) { if (i % 2 == 0) printf("+ "); else printf("* "); } printf("\n");}

Page 83: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

86

Exercise: Modify the following program to produce the output.

for (i=A; i<=B; i++) {

for (j=C; j<=D; j++) {

printf(“*”);

}

printf(“\n”);

}

Output

***************

Page 84: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

87

Exercise Write a program using loop statements

to produce the following output.

Output * ** *** *********

Page 85: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

88

Example Write a program that prints in two columns n

even numbers starting from 2, and a running sum of those values. For example suppose user enters 5 for n, then the program should generate the following table:

Enter n (the number of even numbers): 5Value Sum 2 2 4 6 6 12 8 2010 30

Page 86: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

89

#include <stdio.h>int main(void){ /* Declare variables. */ int n; int sum, i; printf("Enter n "); scanf("%d",&n);

printf("Value \t Sum\n"); sum = 0; for(i=1; i <=n; i++){ sum = sum + 2*i; printf("%d \t %d\n", 2*i, sum); } return 0;}

Page 87: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

90

Compute xy when y is integer Suppose we don’t have pow(x,y)

and y is integer, write a loop to compute xyprintf(“Enter x, y :”);

scanf(“%d %d”, &x, &y);

res=1;

for(i=1; i<=y; i++){

res = res * x;

}

Page 88: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

91

Exercise: sum

Write a program to compute the following

nin

i

...3211

Enter n

total=0;

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

total = total + i ;

print total

ntotal 2...642

Enter n

total=0;

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

total = total + 2 * i ;

print total

Page 89: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

92

Exercise: sum Write a program to compute the following

mm

i

i xxxxxxx

43210

0

Enter x and m

total=0;

for(i=0; i<=m; i++)

total = total + pow(x, i);

print total

Enter x and m

total=0; sofarx=1;

for(i=0; i<=m; i++) {

total = total +sofarx;

sofarx = sofarx * x;

}

print total

Page 90: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

93

Exercise: ln 2

Write a program to compute the following

n

1

7

1

6

1

5

1

4

1

3

1

2

1

1

12ln

Enter nln2=0;for(i=1; i<=n; i++) if ( i % 2 == 0)

ln2 = ln2 - 1.0 / i; else ln2 = ln2 + 1.0 / i; print total

Page 91: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

94

Exercise: ex

Write C program that reads the value of x and n from the keyboard and then approximately computes the value of ex using the following formula:

Then compare your approximate result to the one returned by exp(x) in C library, and print out whether your approximation is higher or lower.

!!3!2!11

32

n

xxxxe

nx

Page 92: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

95

int i, n; double x, ex;double powx, fact;

printf("Enter the value of x and n : ");scanf("%lf %d",&x, &n);

/* Write a loop to compute e^x using the above formula */ex=1.0; fact=1.0; powx=1.0;for(i=1; i<=n; i++){ powx = powx * x; fact = fact * i; ex = ex + powx / fact;}printf("Approx value of e^x is %lf when n=%d\n",ex, n);

/* Check if ex is higher/lower than exp(x) in math lib.*/if(ex < exp(x)) printf("ex est is lower than exp(x)=%lf\n",exp(x));else if (ex > exp(x)) printf("ex est is higher than exp(x)=%lf\n",exp(x));else printf("ex est is the same as exp(x)\n");

Page 93: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

96

Exercise: sin x

Compute sin x using

)!12()1(

!7!5!3!1sin

12753

n

xxxxxx

nn

printf(“Enter x n :”); scanf(“%lf %d”, &x, &n);total=0; powx=x; factx=1;for(i=0; i <= n; i++){ k= 2*n+1; if (i%2==0) total= total - powx/factx; else total= total + powx/factx; powx= powx * x * x; factx = factx * k * (k-1);}printf( “sin(%lf) is %lf\n”,x, total);

Page 94: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

97

For vs. while loop : Convert the following for loop to while loop

for( i=5; i<10; i++) {

printf(“AAA %d \n”, i);

if (i % 2==0) continue;

pritntf(“BBB %d \n”, i);

} i=5;while(i<10) { printf(“AAA %d \n”, i); if (i % 2==0) {

i++; continue;

} pritntf(“BBB %d \n”, i); i++;}

Page 95: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

98

Skip

Study Section 3.5 from the textbook

Page 96: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

99

Lecture++;

Name Addr Content

Lecture 14

Page 97: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

100

3.6 Data Files So far, we used scanf and printf to

enter data by hand and print data on the screen

What if we have 1000 data points to enter? Can we still enter them by hand?

What if the output has several lines and we want to store the output results or use them with other programs?

Page 98: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

101

Read Access to Data Files

Page 99: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

102

Read Access to Data Files #include <stdio.h> File pointer must be defined in C program

FILE *sf; File pointer must be associated with a specific file

using the fopen function If the program and data file are in the same

directory sf = fopen(“sensor1.dat”, “r”);

Else give the full path

sf = fopen(“C:\turgay\H\Teaching\15b-FALL07-cs2073\prog\sensor1.dat”, “r”);

Page 100: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

103

Input file - use fscanf instead of scanf#include <stdio.h> FILE *sf;double t, motion; sf = fopen(“sensor1.dat”, “r”);while( ???? ){

fscanf( sf , “%lf %lf” , &t, &motion);}

Read from Data Files

t

motion

sf

2

4.4

3

3.5

4

6.3

Page 101: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

104

Create New Data Files Write Access to Data Files

#include <stdio.h> File pointer must be defined in C program

FILE *bf; File pointer must be associated with a specific file

using the fopen function If the program and data file are in the same

directory bf = fopen(“balloon.dat”, “w”); Else give the full path bf = fopen(“C:\turgay\H\Teaching\15b-FALL07-cs2073\prog\balloon.dat”, “w”);

Page 102: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

105

Output file - use fprintf instead of printf#include <stdio.h> FILE *bf;double time=6.5, height=5.3;

bf = fopen(“balloon.dat”, “w”);

fprintf( bf , “t: %f h: %f\n”, time, height);

Write to Data Files

time

height

bf

6.5

5.3

7.1

8.3

8.3

3.7 t: 6.500000 h: 5.300000t: 7.100000 h: 8.300000t: 8.300000 h: 3.700000

Page 103: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

106

At the end, Use fclosefclose(sf); fclose(bf);

Page 104: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

107

Example

Read 6 values from a file named my_data.txt and write their average into another file named avg-of-6.txt

6 5

4

2 3 4

5

my_data.txt

program

4

avg-of-6.txt

Page 105: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

108

Example: average grade Suppose we keep the id and three HW

grades of 36 students in a file named grades.txt

Write a program to compute average grade for each student and write each students avg into another file named avg-hw.txt1 5 10 15

2 10 20 30

36 4 6 20

grades.txt

program

1 10 2 20…36 10

avg-hw.txt

Page 106: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

109

Lecture++;

Name Addr Content

Lecture 15

Page 107: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

110

Reading Data FilesWhen to stop Counter controlled loop

First line in file contains count Use for loop

Trailer signal or Sentinel signal Data ends when a special data value is seen -999 Use while loop

End of file controlled loop When file is created EOF is inserted Use while loop feof(fileptr) > 0 when EOF reached fscanf cannot read as many values as you wanted

Page 108: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

111

Check what fopen, fscanf, fprintf return

FILE *fp;fp=fopen(“data.txt”, “r”);if (fp==NULL){ printf(“Program cannot open the file\n”); return -1;}

N=fscanf(fp, “%d %d %d”, &v1, &v2, &v3); /* N is the number of values read successfully */

while(fscanf(fp, “%d %d %d”, &v1, &v2, &v3) == 3) { /* process v1 v2 v3 */}

if (fp=fopen(“data.txt”, “r”)) == NULL){

Page 109: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

112

Counter controlled loopUsually first line in file contains the count

#include <stdio.h>int main(){ FILE *scorefile; int score, count, i, sum=0;

if((scorefile = fopen("scores2.txt","r")) == NULL) ){ printf(“Program cannot open the file\n”); exit(-1); } fscanf(scorefile,"%d", &count); for (i=1; i<=count; i++) {

fscanf(scorefile,"%d", &score); sum = sum + score;

} printf(“Average score %lf \n",(double)sum/count); fclose(scorefile); return(0);}

6567893248563

scores2.txt

Page 110: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

113

Trailer signal or Sentinel signal

#include <stdio.h>int main(){ FILE *scorefile; int score, count=0, i, sum=0;

if((scorefile = fopen("scores3.txt","r")) == NULL) ){ printf(“Program cannot open the file\n”); exit(-1); } fscanf(scorefile,"%d", &score); while(score >= 0) { count++; sum = sum + score; fscanf(scorefile,"%d", &score); } printf(“Average score %lf \n",(double)sum/count); fclose(scorefile); return(0);}

567893248563-999

scores3.txt

Page 111: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

114

End of file controlled loop#include <stdio.h>int main(){ FILE *scorefile; int score, count=0, i, sum=0;

if((scorefile = fopen("scores4.txt","r")) == NULL) ){ printf(“Program cannot open the file\n”); exit(-1); } while (fscanf(scorefile,"%d",&score) == 1) { count++; sum = sum + score; } printf(“Average score %lf \n",(double)sum/count); fclose(scorefile); return(0);}

567893248563

scores4.txt

while (feof(scorefile) <= 0) { fscanf(scorefile,"%d",&score); count++; sum = sum + score;}

Page 112: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

115

Exercise In previous three programs, we

found average. Suppose, we want to also know

how many data points are greater than average.

Change one of the previous programs to determine the number of data points that are greater than average.

Page 113: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

116

Exercise Given a file of integers. Write a program that finds the

minimum number in another file.

Algorithm to find minimum in a file: open file set minimum to a large value while (there are items to read)

read next number x from fileif (x < min) min = x

display the minimumclose file

File

567893248563

Solution available on the next page

Page 114: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

117

#include <stdio.h>

int main(){ FILE *scorefile; int score; int min;

scorefile = fopen("scores.txt","r"); if (scorefile == NULL) printf("Error opening input file\n"); else { min = 110; while (feof(scorefile) <= 0) {

fscanf(scorefile,"%d",&score); if (score < min) min = score;}

}

printf("Min = %d\n",min);

fclose(scorefile); system("pause"); return(0);}

Page 115: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

118

Exercise Given a file of integers. Write a program that searches for

whether a number appears in the file or not.

// algorithm to check for y in a file open file set found to false

while (there are items to read and found is false)read next number x from fileif (x equals y) set found to true

Display found message to user Display not found message to user

close file

File

567893248563

Solution available on the next page

Page 116: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

119

#include <stdio.h>

int main(){ FILE *scorefile; int score, num, found; printf("Please Enter a number\n"); scanf("%d", &num); scorefile = fopen("scores.txt","r"); if (scorefile == NULL) printf("Error opening input file\n"); else{ found = 0; while ((feof(scorefile) <= 0) && (found == 0)) {

fscanf(scorefile,"%d",&score); if (score == num) found = 1; }

if (found == 0) printf("%d does not appear in the file\n",num); else

printf("%d appears in the file\n",num); } fclose(scorefile); system("pause"); return(0);}

Page 117: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

120

Exercise

Change the previous program to count how many times the given number appears in the file?

Instead of fount =1; put fount++;

Page 118: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

121

Read/Write Example Suppose we have a data file that contains worker ID, the

number of days that a worker worked, and the number of hours the worker worked each day.

We would like to find out how much to pay for each worker. To compute this, find the total number of hours for each worker and multiply it by 7 dollar/hour.

For instance, your program should process the following input.txt and generate the corresponding output.txt as follows:

Id numofD hour1 hour2 hour3 Id total-hour payment 1 2 3 8 2 3 5 7 6 3 1 2 4 2 5 1 5 3 1 3 2

input.txt

1 11 772 18 1263 2 144 6 425 6 42

output.txt

program

Page 119: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

122

#include <stdio.h> int main(void){ FILE *infp, *outfp; int ID, numofD, hour, i, total_hour; if ((infp = fopen("input.txt", "r"))==NULL){ printf("Input file cannot be opened\n"); return -1; } if ((outfp = fopen("output.txt", "w"))==NULL){ printf("Output file cannot be opened\n"); return -1; } while(fscanf(infp, "%d %d",&ID, &numofD)==2) {

total_hour=0;for(i=1; i <= numofD; i++){ fscanf(infp,”%d”,&hour); total_hour +=hour;

} fprintf(outfp, "%3d %3d %4d\n",

ID, total_hour, total_hour*7); } fclose(infp); fclose(outfp); return 0;}

Page 120: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

123

Read/write Example Suppose we have a data file that contains student ID and

his/her homework grades for hw1, hw2, hw3, and hw4. We would like to find out min, max and average grade for

each student and write this information into another file. For instance, your program should process the following

input.txt and generate the corresponding output.txt as follows:

1 20 30 28 18 2 35 50 27 36 3 17 20 34 44 4 20 50 14 12 5 33 15 30 20

input.txt

1 18 30 24.00 2 27 50 37.00 3 17 44 28.75 4 12 50 24.00 5 15 33 24.50

output.txt

prog

Id hw1 hw2 hw3 hw4 Id min max avg

Page 121: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

124

#include <stdio.h> int main(void){ FILE *infp, *outfp; int i,ID, hw, max, min; double sum; if ((infp = fopen("input.txt", "r"))==NULL){ printf("Input file cannot be opened\n"); return -1; } if ((outfp = fopen("output.txt", "w"))==NULL){ printf("Output file cannot be opened\n"); return -1; } while(fscanf(infp, "%d %d",&ID, &hw)==2) { sum=max=min=hw; for(i=1; i <= 3; i++){ fscanf(infp,”%d”,&hw); sum = sum + hw; if (hw > max) max = hw; if (hw < min) min = hw; } fprintf(outfp, "%3d \t %3d \t %4d \t %3.2lf\n",

ID, min, max, sum/4); } fclose(infp); fclose(outfp); return 0;}

Page 122: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

Eliminate out of order records Suppose we have a data file that has 5 columns in each row,

namely student ID, hw1, hw2, hw3, hw4. We are told that most rows in this file are sorted in an

increasing order based on the ID field. Write a program to determine the students whose IDs are not in order and print the IDs and homework grades of such students into another file.

125

2 4 3 3 2

3 3 1 1 1

5 3 5 8 3

1 4 4 1 5

7 3 5 3 3

8 1 2 4 7

4 5 4 6 3

10 2 3 2 9

12 4 8 3 4

1 4 4 1 5

4 5 4 6 3program

Page 123: 1 Control Structures and Data Files Turgay Korkmaz Office: SB 4.01.13 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: korkmaz

126

More example

Study 3.7 and 3.8 from the textbook