1. C Programming
a Q & A Approach
by H.H. Tan, T.B. D’Orazio, S.H. Or & Marian M.Y. Choy
Chapter 3
The Basics of C – Math Functions and
Character File Input/Output
2. 4
Programming Example
Calculate the surface area of a triangle
the length of the two sizes
the angle between the two sizes
all data are input from user
Procedure of the program
figure out the right formula:
define the right data type
convert the formula to C expression
output the results
1
l
2
l
1 2
0.5 sin( )
S l l
9. Step6:Display result
Introduction to Programming in C 11
Test Running result:
Please input length1:
5
Please input length2:
8
Please input angle:
90
The area of this triangle is:20.000000
10. 12
Use of Double
Double can carry a large number of digits
important when doing a large number of
calculations
more memory is required
e.g. computing 100
With 5 significant figures
(3.1416)100
= 5.189061599 * 1049
Using 8 significant digits
(3.1415926)100
= 5.1897839464 * 1049
Accuracy is reduced after numerous arithmetic
operations
11. 13
Item float double long double
Memory
used
4 bytes = 32 bits 8 bytes = 64 bits 10 bytes = 80
bits
Range of
values
1.1754944E - 38 to
3.4028235E + 38
2.2250738E - 308
to 1.7976935E +
308
Approximately
1.0E - 4931
to 1.0E +
4932
Precision 6 15 19
printf
format
%f, %e, %E, %g,
%G
%lf, %e, %E, %g,
%G
%Lf, %Le,
%LE, %Lg,
%LG
12. Example for %g %f %e
Introduction to Programming in C 14
Memory
Errors
13. 15
C Mathematical Library Functions
Input argument(s) x or y and return
values are of double type
argument be in radians, not degrees
FUNCTION NAME CALCULATING
sin(x) sine of x, x is in radians
exp(x) natural exponential of x
log(x) natural logarithm of x
sqrt(x) square root of x
pow(x, y) x raised to the power of y
15. 17
Function
name
Example Description
abs(x) y=abs(x); absolute value of an int type argument, x and y
are of type int (Note: needs #include
<stdlib.h> not math.h)
fabs(x) y=fabs(x); absolute value of a double type argument, x and
y are of type double (Note: needs #include
<stdlib.h> not math.h)
sin(x) y=sin(x); sine of an angle in radians, x and y are of type
double
cos(x) y=cos(x); cosine of an angle in radians, x and y are of type
double
tan(x) y=tan(x); tangent of an angle in radians, x and y are of
type double
log(x) y=log(x); natural logarithm of x, x and y are of type double
log10(x) y=log10(x)
;
logarithm to the base 10 of x, x and y are of type
double
16. 18
3.2 Single Character Data
Character type, char, refers to more than
just lowercase and uppercase letters
Graphic characters such as !, #, and ^.
Escape sequences (like n and r) also are
regarded as single characters
18. 20
Character
Declared with
char variable1, variable2, variable3, . . .;
e.g.
char c1, c2, c3, c4, c5, c6, c7,
c8, c9, c10, c11;
Assignment of char
enclose the value(constant) in single quotes, ‘
‘, e.g. c1 = 'g';
19. 21
Character Processing
C regards escape sequences as a single
character, e.g.
c3 = 'n';
To print characters
printf ("%c %c n", c1, c2);
C treats characters with their integer values
printf ("n%d %dn", c4, c5);
If c4, c5 were input as ‘x’ and ‘p’, the ASCII
values 120 and 112, are printed
20. 22
Read Characters from Keyboard
Using the scanf with %c
scanf ("%c%c", &c4, &c5);
We can not get space, Enter … white-space
characters from keyboard
21. 23
Read Characters from Keyboard
Ο scanf function classifies what is in the
format string into three categories:
1. Conversion / format specifiers (begins with a
%)
2. White-space characters (which for scanf is
not just a space, scanf treats Tab, and Enter
[newline n] also as white spaces)
3. Non-white-space characters
22. 24
Read Characters from Keyboard
Ο When scanf has a space in its string literal, that space causes
scanf to skip over one or more white-space characters in the
input buffer to get to the next non-white-space character
Ο when reading characters, must make sure no white space in
string literal for scanf
● For example,
scanf ("%c%c", &c1, &c2);
will not accept
as input!
23. 25
getche
Form
char c3=getche();
Deals directly with the operating system
Does not require Enter key to be pressed
Similar functions to input a char:
getch getchar
24. Homework 5
Make a program or programs to input a
char with:
scanf
getch
getche
getchar
Draw a conclusion after compare the
difference of four functions in running
results.
Introduction to Programming in C 26
25. 27
3.3 File Processing
Typical file processing procedures:
Opening a file
• When program is being executed, it will
search for a file with that name
Reading/writing data from a file
• Read using the fscanf( ) function
• Write using the fprintf()
Close the file
26. 28
//varialbes
double xx ;
int ii, kk;
FILE *fp;
//open file
fp = fopen ("AB.txt","r");
//input from file
fscanf (fp,"%d",&ii);
fscanf (fp,"%d%lf",&kk,&xx);
//close file
fclose (fp);
//display on the screen.
printf ("ii=%5dnkk=%5dnxx=%9.3lfn",ii,
kk, xx);
36
123 456.78
Output
Input file AB.txt
28. 30
File Pointers
Pointer variables holding address to the file
FILE *inptr;
inptr is the file pointer
FILE is a derived data type defined in stdio.h
Use fopen to create a link between a disk file and a file pointer, thus
accessing the file content
file_pointer = fopen (file_name, access_mode);
e.g.
inptr = fopen (“C3_4.IN","r");
file_name and the access_mode are in string literals
“c3_4.in” is the actual disk file name to be opened
The file pointer being received is then used to handle the actual file
“r” means that we want to read data, i.e., read mode access
Use “w” for write access
29. FILE *fopen(const char
*filename, const char *mode)
Sr.No. Mode & Description
1
"r"
Opens a file for reading. The file must exist.
2
"w"
Creates an empty file for writing. If a file with the same name already
exists, its content is erased and the file is considered as a new
empty file.
3
"a"
Appends to a file. Writing operations, append data at the end of the
file. The file is created if it does not exist.
4
"r+"
Opens a file to update both reading and writing. The file must exist.
5
"w+"
Creates an empty file for both reading and writing.
6
"a+"
Opens a file for reading and appending.
31
30. 32
File Processing
Use fscanf() to read data from a file
fscanf(file_pointer, format_string,
argument_list);
Reads the contents of the file indicated by file_pointer according
to the conversion specifications in format_string.
Basically similar to that of scanf, only that the content is now
being read from the file, e.g.
fscanf(inptr, "%d %lf",&kk,&xx);
Although C will automatically close all open files after execution,
it is still recommended to close a file manually, using the fclose()
fclose(file_pointer);
example
fclose(inptr);
33. Files in the project
Introduction to Programming in C 35
Before
execution
After
execution
34. 36
File Processing
Use the fprintf() function to write data to a file.
fprintf(file_pointer, format_string, argument_list);
example
fprintf(myfile," Week = %5dn Year = %5dn",week, year);
Note we use the mode string “w” here for write
access
36. 38
3.5 Applications -Example 1
7.0
5.0
l1
h1
l2
h2
h3
l3
We have four right triangles, the vertical length of the next triangle is half of the
previous one; the horizontal length of the next triangle is incremented 1 from the
previous one. Initially, the vertical and horizontal length of the first right triangle is
7.0 and 5.0. You are asked to write a program to calculate the dimension of each
triangle and their surface area.
37. 39
Program developing procedure
Begin // include some preprocessing directives, stdio.h, math.h, etc
Declare variables //choose right variable names and data types
initialize horizontal leg length of the first triangle // can be done during declaration
initialize vertical leg length of the first triangle
Calculate area of first triangle // convert math expression to C
Calculate horizontal/vertical leg lengths of second triangle // using correct C operators
Calculate area of second triangle
Calculate horizontal /vertical leg lengths of third triangle
Calculate area of third triangle
Calculate horizontal /vertical leg lengths of fourth triangle
Calculate area of fourth triangle
Print results onto the screen /file
End // does the program need to return some value
3.5 Applications
38. 40
#include<stdio.h>
void main(void)
{
double horiz_leg, vert_leg, area1,area2,area3,area4;
horiz_leg = 5.0;
vert_leg = 7.0;
area1 = horiz_leg * vert_leg * 0.50;
horiz_leg += 1.0;
vert_leg /= 2.0;
area2 = horiz_leg * vert_leg * 0.50;
horiz_leg += 1.0;
vert_leg /= 2.0;
area3 = horiz_leg * vert_leg * 0.50;
horiz_leg += 1.0;
vert_leg /= 2.0;
area4 = horiz_leg * vert_leg * 0.50;
printf("nn"
"First triangle area t= %6.2f n"
"Second triangle area t= %6.2f n"
"Third triangle area t= %6.2f n"
"Fourth triangle area t= %6.2f n",area1,area2,area3,area4);
}
How to modify the
code in order to print
the results onto a file
too?
39. 41
Assume that one person can push with the force of f=0.8kN
and that we have a car of m=1000kg. Write a program to
calculate the final velocity of the car by taking values of
number of people pushing the car and the distance they
pushed.
Figure out the right formula to get the final velocity
Determine the origin of the required information
number of people n <= input
distance s <= input
Define variables
read values for f,m from file1 on disk
read values for n,s from user( keyboard)
Calculate the results for v
Display the values on window and save the values in file2 on disk
3.5 Applications - Exampel2
2
2
1
mv
Fs m
Fs
v /
2
n
F f
40. 42
Key Points (Home work)
math.h should be included
declare right type for different variables
distance => float or double
people => integer
velocity => float or double
using scanf to get values from user, fscanf to get values from
file
give information on what the user should provide
variable address operator &
Output all of the values and results with printf on window, and
save all of the values and results with fprintf in file.
3.4 Applications - Exampel2
41. Homework-5
Study the source code for
Applications -Example 1
Finish Applications - Exampel2
Submit the source code as *.c or
*.cpp
Submit the snapshot of the
running window
Submit the input file and output
files
Introduction to Programming in C 43
Editor's Notes
#21:There is another way to print characters onto screen putchar()
#34:fopen is used to open the output file and to create a link between the file pointer and file