Professional Documents
Culture Documents
Control Structures and Data Files: CS 2073 Computer Programming W/eng. Applications
Control Structures and Data Files: CS 2073 Computer Programming W/eng. Applications
Control Structures and Data Files: CS 2073 Computer Programming W/eng. Applications
Turgay Korkmaz
Office: SB 4.01.13
Phone: (210) 458-7346
Fax: (210) 458-4437
e-mail: korkmaz@cs.utsa.edu
web: www.cs.utsa.edu/~korkmaz
1
Name Addr Content
Lecture++;
Lecture 7
2
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)
3
Pseudo-code Notation and
Flowchart Symbols
4
Structured Programming
Use simple control structures to organize the
solution to a problem
Sequence
no yes
Selection
no
Repetition yes
5
Sequence
6
Selection
7
Repetition
8
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
9
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
10
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+c; 1 Y
10 K
Mixing with arithmetic op
X+Y >= K/3
12
Logical Operators
! not !(x==0)
&& and (x>=0) && (x<=10)
|| or (x>0) || (x<0)
A B A && B A || B !A !B
False False False False True True
False True False True True False
True False False True False True
True True True True False False
13
Examples
A<B && C>=5
4 A
A+B * 2 < 5 && 4>=A/2 B
2
A<B || C<B && A-2 < 10 6 C
A < B < C ????
A<B<C is not the same as
(A<B) && (B<C)
14
Precedence for Arithmetic,
Relational, and Logical Operators
15
Exercise
Assume that following variables are declared
a = 5.5 b = 1.5 k = -3
Are the following true or false
a < 10.0 + k
a + b >= 6.5
k != a-b
!(a == 3*b)
a<10 && a>5
fabs(k)>3 || k<b-a
16
Exercise: Logical Circuit
y1 = x1 && x2;
x1 y1
AND y2 = x3 || x4;
x2 z1
OR y3 = !x5;
x3 y2 z1 = y1 || y2;
OR
x4 z2 = y2 && y3
AND z2 Without using y1, y2, y3
y3
x5 NOT z1 = x1 && x2 || (x3 || x4);
z2 = (x3 || x4) && !x5;
Write a program that reads x1, x2, x3, x4, x5 and computes/prints z1, z2 17
Exercise
a
b
C
18
Name Addr Content
Lecture++;
Lecture 8
19
3.3 Selection Statements
if
if else
switch
20
if statement
if(Boolean expression)
statement; /* single statement */
if(Boolean expression) {
/* more than one statement */
statement1;
…
statement n;
}
21
if statement - examples
if (x > 0)
k++; Name Addr Content
x 9
if(x > 0) { y 5
y = sqrt(x); k 4
k++;
}
if(Boolean expression)
statement;
else
statement;
if(Boolean expression) {
statement block
} else {
statement block
}
23
if else statement
What does the following program do?
Assume that x, y, temp are declared.
Name Addr Content
if (x > y) x 9
y 5
temp = x; temp ?
if (x > y) {
Name Addr Content
max = x;
min = y;
x 9 9 3 3 6 6
} else {
y 5 5 8 8 6 6
max = y; max ? 9 9 8 8 6
min = x; min ? 5 5 3 3 6
}
25
if else statement
Split the following statement into two separate if
statements
if (x > y) if (x > y)
temp = x; temp = x;
else
temp = y; if (x <= y)
temp = y;
26
Flow chart for previous slide
if (x > y)
if (x > y) T
temp = x; x>y
temp = x;
else
temp=x
temp = y; if (x <= y)
temp = y;
T
x>y
T
x <= y
27
nested if-else
if(x > y) { F T
x>y
if(y < z) {
k++; T
F y<z
}else
else { j++
m++;
else } m++ k++
} else {j++;
j++;
}
28
Exercise
int x=9, y=7, z=2, k=0, m=0, j=0; F T
x>y
if(x > y)
if(y < z)
T
k++; F y<z
j++
else
m++;
else k++
m++
j++;
29
Exercise: Find the value of a
T
a>0
int a = 750;
if (a>0) T
a >= 1000
if (a >= 1000)
a = 0;
else a =a+3 T
a < 500
if (a <500) a=0
a =a*2;
else a =a*10 a =a*2
a =a*10;
else
a =a+3;
30
Exercise: Find the value of a
int a = 750;
if (a>0) { a>0
T
if (a >= 1000) {
a = 0;
T
} else { a >= 1000
if (a <500) {
a =a*2; a =a+3 T
a < 500
} else { a=0
a =a*10;
} a =a*10 a=a*2
}
} else {
a =a*3;
} 31
Indentation
int a = 750; int a = 750;
if (a>0) if (a>0)
if (a >= 1000) if (a >= 1000)
a = 0; a = 0;
else else
if (a <500) if (a <500)
Good a=a*2; a=a*2;
else else
a=a*10; a=a*10; Not good
else else
a =a+3; a = a+3;
32
Indentation (cont’d)
What is the output of the following programs
int a = 5, b = 3;
if (a>10) if (a>10) {
a = 50; a = 50;
b = 20; Not good b = 20;
}
printf(" a = %d, b = %d\n",a, b); printf(" a = %d, b = %d\n",a, b);
if (a>10) if (a>10) {
a = 50; a = 50;
b = 20; Good b = 20;
}
printf(" a = %d, b = %d\n",a, b); printf(" a = %d, b = %d\n",a, b);
33
Exercise: Region in a plane
Write a program that reads a point
(x, y) from user and prints its region
For example
Region 2 Region 1 Enter x y: 3 -1
This point is in Region 4
Region 3 Region 4
Enter x y: -1 -5
This point is in region 3
Enter x y: 0 5 ???????
34
Name Addr Content
Lecture++;
Lecture 9
35
Switch Statement
switch(expression) {
case constant:
statement(s);
break;
case constant:
statement(s);
break;
default: /* default is optional */
statement(s);
}
36
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;
} 37
Exercise
Convert the switch statement into if statement.
switch (op_code) {
case ‘N’: if (op_code == ‘N’)
printf(“Normal\n”); printf(“Normal\n”);
break; else if (op_code == ‘M’)
case ‘M’: printf(“Maintenance Needed\n”);
printf(“Maintenance Needed\n”); else
break; printf(“Error\n”);
default:
printf(“Error\n”);
break;
}
38
Exercise
Convert the following nested if/else statements to a
switch statement switch(rank) {
case 1:
if (rank==1 || rank==2)
printf("Lower division \n"); case 2:
else printf("Lower division \n");
{ break;
if (rank==3 || rank==4) case 3:
printf("Upper division \n");
else case 4:
{ printf("Upper division \n");
if (rank==5) break;
printf("Graduate student \n"); case 5:
else
printf("Invalid rank \n"); printf("Graduate student \n");
} break;
} default:
printf("Invalid rank \n");
} 39
More selection examples
40
Write if-else statement
T
score > 70
T T
age > 18 age > 18
41
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”);
}
42
get b, c from user
a=b+c
F T
a <= 10 and b-c > 6
Print “RIGTH”, a, b, c
c != b T b= 5 + c * 2
Print “LEFT-RIGTH”, a, b, c T
F F a*b<=12
c= 5 + c * 2
Print “RIGTH-LEFT”, a, b, c
Print “LEFT-LEFT”, a, b, c a= 10 - c * c
b= a * -c
c = a+b
Print “FINAL”, a, b, c
45
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
46
Another if-else flowchart
if( A > 8) { T
A=b+c; A>8
B=b*c;
if(A > 8) T
T A<4
B=b/c; A<5
A=b-c;
if(A < 5) T
A>8
B=b+c; A=B
else B=b/c
B=b%c;
A=B;
47
}
Exercise: Assign Letter Grade
Given a score and the following grading scale write a
program to find the corresponding grade.
90-100 A
80-89 B
70-79 C
60-69 D
0-59 F
48
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");
49
Solution-2
if ((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");
50
Triangle inequality
Suppose we want to check if we can
make a triangle using a, b, c
51
Charge for money transfer
Suppose you transfer $N and bank’s
charge occurs as follows.
$10 if N $500
$10 2% of N if 500 N 1000
cos t
$15 0.1% of N if 1000 N 10000
$30 Otherwise
Write a program that reads N and
computes cost
52
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
2
(1 ) if 0 1
2 2
AvgDelay 1 2(1 )
if 1
53
#include <stdio.h>
int main(void)
{
/* Declare variables. If needed, you can declare more*/
double rho, mu, sigma, AvgDelay;
Lecture++;
Lecture 10
56
Loop (Repetition) Structures
60
Problem: Conversion table
degrees radians
Degrees to Radians
0 0.000000
10 0.174533
20 0.349066
30 0.523599
…
340 5.934120
350 6.108653
radians = degrees * PI / 180;
360 6.283186
61
#include <stdio.h>
Sequential #define PI 3.141593
int main(void)
Solution {
int degrees=0;
double radians;
printf("Degrees to Radians \n");
degrees = 0;
radians = degrees*PI/180;
printf("%6i %9.6f \n", degrees, radians);
degrees = ???
radians = degrees*PI/180; degrees = 10;
printf("%6i %9.6f \n", degrees, radians); radians = degrees*PI/180;
printf("%6i %9.6f \n", degrees, radians);
degrees = 20;
radians = degrees*PI/180;
printf("%6i %9.6f \n", degrees, radians);
…
Not a good solution degrees = 360;
radians = degrees*PI/180;
printf("%6i %9.6f \n", degrees, radians);
} 62
Loop
Solution
#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees=0;
double radians;
printf("Degrees to Radians \n");
64
while statement
while(expression)
statement;
while(expression) {
statement;
statement;
…
}
65
Example
#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees=0;
double radians;
int main(void)
{
int degrees=0;
double radians;
69
Example
#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees;
double radians;
initialize
test
Increment or
decrement
true
statement(s)
statement(s)
71
Examples
int sum =0, i;
for( i=1 ; i < 7;i=i+2 ){ ?135 7 i
sum = sum+i;
} 0 1 4 sum
9
int fact=1, n;
for( n=5 ; n>1 ; n--){
fact = fact * n;
} 5
n
n--; means n=n-1; 1 fact
n++; means n=n+1;
72
Exercise
Determine the number of times that each of the following
for loops are executed.
73
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; 0 2 6 sum1
sum2 = 0;
for( k = 1; k < 5; k++) { 0 1 4 sum2
if( k % 2 == 0)
sum1 =sum1 + k; 1 2 3 4 5 k
else
sum2 = sum2 + k;
}
printf(“sum1 is %d\n”, sum1); sum1 is 6
printf(“sum2 is %d\n”, sum2); sum2 is 4
74
For vs. while loop
Convert the following for loop to while loop
i=5;
while(i<10){
pritntf(“ i = %d \n”, i);
i++;
}
75
break statement
break;
terminates loop
execution continues with the first statement following the
loop
sum = 0; sum = 0;
k=1;
for (k=1; k<=5; k++) { while (k<=5) {
scanf(“%lf”,&x); scanf(“%lf”,&x);
if (x > 10.0) if (x > 10.0)
break; break;
sum +=x;
sum +=x; k++;
} }
printf(“Sum = %f \n”,sum); printf(“Sum = %f \n”,sum);
76
continue statement
continue;
forces next iteration of the loop, skipping
78
Example: A man walks
Suppose a man (say, A) stands N
at (0, 0) and waits for user to
give him the direction and
distance to go.
User may enter N E W S for
E
north, east, west, south, and W
any value for distance.
When user enters 0 as
direction, stop and print out
S
the location where the man
stopped
79
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 */ 80
Name Addr Content
Lecture++;
Lecture 13
81
More loop examples
82
Exercise
What is the output of the
following program? Output
83
Exercise
What is the output of the
following program? Output
84
Example: nested loops to
generate the following output
What/how
int i, j; do you need to
change in
for(i=1; th following
i <= 5; i++){
i=1 * program?
printf("i=%d ", i);
for(j=1; j <= i; j++) {
i=2 ++ for if
(i=1; i<=5; i++) {
(i % 2 == 0)
for (j=1; j<=i;
printf("+ "); j++){
i=3 *** else printf(“*”);
} printf("* ");
i=4 ++++ }printf(“\n”);
} printf("\n");
i=5 ***** }
85
Exercise: Modify the following
program to produce the output.
86
Exercise
Write a program using loop statements to
produce the following output.
Output
*
**
***
****
*****
87
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): 5
Value Sum
2 2
4 6
6 12
8 20
10 30
88
#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;
} 89
Compute xy when y is integer
Suppose we don’t have pow(x,y) and y
is integer, write a loop to compute xy
printf(“Enter x, y :”);
scanf(“%d %d”, &x, &y);
res=1;
for(i=1; i<=y; i++){
res = res * x;
} 90
Exercise: sum
Write a program to compute the following
n
i
i 1
1 2 3 ... n total 2 4 6 ... 2n
Enter n Enter n
total=0; total=0;
x i
i 0
x 0
x1
x 2
x 3
x 4
x m
Enter x and m
Enter x and m total=0; sofarx=1;
for(i=0; i<=m; i++) {
total=0;
total = total +sofarx;
for(i=0; i<=m; i++)
sofarx = sofarx * x;
total = total + pow(x, i); }
print total print total 92
Exercise: ln 2
Write a program to compute the following
1 1 1 1 1 1 1 1
ln 2
1 2 3 4 5 6 7 n
Enter n
ln2=0;
for(i=1; i<=n; i++)
if ( i % 2 == 0)
ln2 = ln2 - 1.0 / i;
else
ln2 = ln2 + 1.0 / i;
print total 93
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:
2 3 n
x x x x
e 1
x
1! 2! 3! n!
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.
94
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"); 95
Exercise: sin x
Compute sin x using
3 5 7 2 n 1
x x x x x
sin x (1) n
1! 3! 5! 7! (2n 1)!
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);
96
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++;
97
}
Skip
Study Section 3.5 from the textbook
98
Name Addr Content
Lecture++;
Lecture 14
99
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?
100
Read Access to Data Files
101
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”);
102
Read from Data Files
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);
} 2 3 4 t
bf = fopen(“C:\turgay\H\Teaching\15b-FALL07-cs2073\prog\balloon.dat”, “w”);
104
Write to Data Files
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);
106
Example
Read 6 values from a file named
my_data.txt and write their average
into another file named avg-of-6.txt
65 4
4 avg-of-6.txt
program
234
5
my_data.txt
107
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.txt
1 5 10 15 1 10
2 20
2 10 20 30 program …
… 36 10
36 4 6 20 avg-hw.txt
grades.txt 108
Name Addr Content
Lecture++;
Lecture 15
109
Reading Data Files
When 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
110
Check what
fopen, fscanf, fprintf return
FILE *fp;
fp=fopen(“data.txt”, “r”);
if (fp==NULL){ if (fp=fopen(“data.txt”, “r”)) == NULL){
printf(“Program cannot open the file\n”);
return -1;
}
#include <stdio.h>
int main()
{
FILE *scorefile;
int score, count, i, sum=0; 6
if((scorefile = fopen("scores2.txt","r")) == NULL) ){
56
printf(“Program cannot open the file\n”); 78
exit(-1); 93
} 24
fscanf(scorefile,"%d", &count); 85
for (i=1; i<=count; i++) { 63
fscanf(scorefile,"%d", &score);
sum = sum + score; scores2.txt
}
printf(“Average score %lf \n",(double)sum/count);
fclose(scorefile);
return(0);
}
112
Trailer signal or Sentinel signal
#include <stdio.h>
int main()
{
FILE *scorefile;
int score, count=0, i, sum=0; 56
78
if((scorefile = fopen("scores3.txt","r")) == NULL) ){ 93
printf(“Program cannot open the file\n”); 24
exit(-1);
85
}
fscanf(scorefile,"%d", &score); 63
while(score >= 0) { -999
count++; scores3.txt
sum = sum + score;
fscanf(scorefile,"%d", &score);
}
printf(“Average score %lf \n",(double)sum/count);
fclose(scorefile);
return(0); 113
}
End of file controlled loop
#include <stdio.h>
int main()
{
FILE *scorefile;
int score, count=0, i, sum=0;
115
Exercise
Given a file of integers. Write a program that finds the minimum
number in another file.
116
#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);
} 117
Exercise
Given a file of integers. Write a program that searches for
whether a number appears in the file or not.
120
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
1 payment2 3 8 1 11 77
2 3 5 7 6 progra 2 18 126
3 1 2 m 3 2 14
4 2 5 1 4 6 42
5 3 1 3 2 5 6 42
input.txt output.txt
121
#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; 122
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:
123
#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; 124
}
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.
2 4 3 3 2
3 3 1 1 1
5 3 5 8 3
1 4 4 1 5
1 4 4 1 5
program 4 5 4 6 3
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
125
More example
Study 3.7 and 3.8 from the textbook
126