Title: Turgay Korkmaz
1CS 2073 Computer Programming w/ Eng. Applications
Ch 2 Simple C Programs
Turgay Korkmaz Office SB 4.01.13 Phone (210)
458-7346 Fax (210) 458-4437 e-mail
korkmaz_at_cs.utsa.edu web www.cs.utsa.edu/korkmaz
2Name Addr Content
Lecture 3
Lecture
32.1 Program Structure
4/-----------------------------------------/ /
Program chapter1_1 / /
This program computes the / /
distance between two points.
/ include ltstdio.hgt include ltmath.hgt int
main(void) / Declare and initialize
variables. / double x11, y15, x24,
y27, side_1, side_2, distance /
Compute sides of a right triangle. / side_1
x2 - x1 side_2 y2 - y1
distancesqrt(side_1side_1 side_2side_2)
/ Print distance. / printf("The distance
between the two " "points is 5.2f \n",
distance) return 0 / Exit program.
/ /-----------------------------------------/
Comments Preprocessor, standard C library every
C program must have main function, this one takes
no parameters and it returns int value ? begin
Variable declarations, initial values (if
any) Statements must end with
indentation indentation
indentation return 0 ? end of function
5General Form
- The main function contains two types of commands
declarations and statements - Declarations and statements are required to end
with a semicolon () - Preprocessor directives do not end with a
semicolon - To exit the program, use a return 0 statement
preprocessing directives int main(void) declara
tions statements
6Another Program
/
/ / Program chapter1 / /
This program computes the sum of two numbers
/ include ltstdio.hgt int main(void) /
Declare and initialize variables. / double
number1 473.91, number2 45.7, sum /
Calculate sum. / sum number1
number2 / Print the sum. /
printf(The sum is 5.2f \n, sum)
system("pause") / keep DOS window on the
screen/ return 0 / Exit program.
/ /
/
72.2 Constants and Variables
- What is a variable in math?
- f(x) x2x4
- In C,
- A variable is a memory location that holds a
value - An identifier or variable name is used to
reference a memory location.
8Memory double x11,x27,distance
name
address
Memory - content
1 00000001
7 00000111
? 01001101
11 12 13 14 15 16
How many memory cells does your computer have?
Say it says 2Gbyte memory? 1K103 or 210
1024 1M106 or 220 10242 1G109 or
230 10243
x1
x2
distance
9Memory Snapshot
Name Addr Content
x1 1
y1 5
x2 4
y2 7
side_1 ?
side_2 ?
distance ?
10Rules for selecting a valid identifier (variable
name)
- Must begin with an alphabetic character or
underscore (e.g., abcABC_) - May contain only letters, digits and underscore
(no special characters _at_) - Case sensitive (AbC, aBc are different)
- Cannot use C keywords as identifiers (e.g., if,
case, while)
11Are the following valid identifiers?
12C Numeric Data Types
13Example Data-Type Limits
14C Character Data Type char
char result Y
In memory, everything is stored as binary value,
which can be interpreted as char or integer.
Examples of ASCII Codes
15Memory
address
name
Memory - content
How to represent a ? char My_lettera int
My_number 97 Always we have 1s and 0s in the
memory. It depends on how you look at it? For
example, 01100001 is 97 if you look at it as
int, or a if you look at it as char 3 is not
the same as 3 How to represent 2.5?
a 01100001
97 01100001
? 01001101
0 1 2 3 4 5 6
My_letter
My_number
16Program to Print Values as Characters and Integers
17Constants
- A constant is a specific value that we use in our
programs. For example - 3.14, 97, a, or hello
- In your program,
- int a 97
- char b a
- double area, r2.0
- double circumference
- area 3.14 rr
- circumference 2 3.14 r
01100001
01100001
?
?
2.0
a b area circumference r
18Symbolic Constants
- What if you want to use a better estimate of ??
- For example, you want 3.141593 instead of 3.14.
- You need to replace all by hand ?
- Better solution, define ? as a symbolic constant,
e.g. - define PI 3.141593
-
- area PI r r
- circumference 2 PI r
- Defined with a preprocessor directive
- Compiler replaces each occurrence of the
directive identifier with the constant value in
all statements that follow the directive
192.3 Assignment Statements
- Used to assign a value to a variable
- General Form
- identifier expression
- / means assign expression to identifier /
- Example 1
- double sum 0
- Example 2
- int x
- x5
- Example 3
- char ch
- ch a
0
5
a
sum x ch
20Assignment examples (contd)
- Example 3
- int x, y, z
- x y 0
- right to left!
- Z 11
- Example 4
- yz
- y5
0
0
2
x y z
2
5
21Assignment examples with different types
?
5
2.3
2
- int a, b5
- double c2.3
-
- ac / data loss /
- cb / no data loss /
a b c
5.0
- long double, double, float, long integer,
integer, short integer, char - Data may be lost. Be careful!
- ? No data loss
22Exercise swap
- Write a set of statements that swaps the contents
of variables x and y
x
3
x
5
5
y
3
y
Before
After
23Exercise swap
Before
24Exercise swap
Before
- Will the following solution work, too? temp y
- yx
- xtemp
- Write a C program to swap the values of two
variables
25Name Addr Content
Lecture 4
Lecture
26Arithmetic Operators
- Addition sum num1 num2
- Subtraction - age 2007 my_birth_year
- Multiplication area side1 side2
- Division / avg total / number
- Modulus lastdigit num 10
- Modulus returns remainder of division between two
integers - Example 52 returns a value of 1
- Binary vs. Unary operators
- All the above operators are binary (why)
- - is an unary operator, e.g., a -3 -4
27Arithmetic Operators (contd)
- Note that id exp means assign the result of
exp to id, so - XX1 means
- first perform X1 and
- Assign the result to X
- Suppose X is 4, and
- We execute XX1
4
X
5
28Integer division vs Real division
- Division between two integers results in an
integer. - The result is truncated, not rounded
- Example
- int A5/3 ? A will have the value of 1
- int B3/6 ? B will have the value of 0
- To have floating point values
- double A5.0/3 ? A will have the value of
1.666 - double B3.0/6.0 ? B will have the value of 0.5
29Implement a program that computes/prints simple
arithmetic operations
- Declare a2, b5, c7, d as int
- Declare x5.0, y3.0, z7.0, w as double
- d ca Print d
- d c/a Print d
- w z/x Print w
- d z/x Print d
- w c/a Print w
- aa1 Print a
- try other arithmetic operations too..
30Mixed operations and Precedence of Arithmetic
Operators
int a46/32 ? a? int b(46)/32 ? b?
a 422 44 8
b 10/32 32 6
5 assign
Right to left
31Extend the previous program to compute/print
mixed arithmetic operations
Declare a2, b5, c7, d as int Declare
x5.0, y3.0, z7.0, w as double d
aca Print d d bc/a Print d w
yz/xb Print w d z/x/ya Print d w
c/(ac)/b Print w aa1b/3 Print a try other
arithmetic operations too..
32Increment and Decrement Operators
- Increment Operator
- post increment x
- pre increment x
- Decrement Operator --
- post decrement x--
- pre decrement --x
But, the difference is in the following example.
Suppose x10 A x - 5 means Ax-5 xx1
so, A 5 and x11 B x - 5 means xx1
Bx-5 so, B6 and x11
33Abbreviated Assignment Operator
- operator example equivalent statement
- x2 xx2
- - x-2 xx-2
- xy xxy
- / x/y xx/y
- xy xxy
- !!! x 42/3 ? x x42/3 wrong
- xx(42/3) correct
34Precedence of Arithmetic Operators (updated)
35Writing a C statement for a given MATH formula
- Area of trapezoid
- area base(height1 height2)/2
- How about this
36Exercise
Tension 2m1m2 / m1 m2 g
wrong
Tension 2m1m2 / (m1 m2) g
- Write a C statement to compute the following
f (xxx-2xxx-6.3)/(xx0.05x3.14)
37Exercise Arithmetic operations
a b c x y
?
?
5
?
?
- Show the memory snapshot after the following
operations by hand - int a, b, c5
- double x, y
- a c 2.5
- b a c 2 - 1
- x (5 c) 2.5
- y x (-3 a) / 2
-
- Write a C program and print out the values of
a, b, c, x, y and compare them with the ones that
you determined by hand.
a 12 b 3 c 5 x 25.0000 y 43.0000
38Exercise Arithmetic operations
- Show how C will perform the following statements
and what will be the final output? - int a 6, b -3, c 2
- c a - b (a c 2) a / 2 b
- printf("Value of c d \n", c)
39Step-by-step show how C will perform the
operations
-
- c 6 - -3 (6 2 2) 6 / 2 -3
- c 6 - -3 (6 4) 3 -3
- c 6 - -3 10 -9
- c 6 - -30 -9
- c 36 -9
- c 27
- output
- Value of c 27
40Step-by-step show how C will perform the
operations
- int a 8, b 10, c 4
-
- c a 5 / 2 -b / (3 c) 4 a / 2 b
-
- printf("New value of c is d \n", c)
41Exercise reverse a number
- Suppose you are given a number in the range 100
999 - Write a program to reverse it
- For example,
- num is 258
- reverse is 852
int d1, d2, d3, num258, reverse d1 num /
100 d2 num 100 / 10 d3 num 10 reverse
d3100 d210 d1 printf(reverse is d\n,
reverse)
d1 num / 100 d3 num 10 reverse num
(d1100d3) d3100 d1
42Name Addr Content
Lecture 5
Lecture
432.4 Standard Input and Output
- Output printf
- Input scanf
- Remember the program computing the distance
between two points! - / Declare and initialize variables. /
- double x11, y15, x24, y27,
- side_1, side_2, distance
- How can we compute distance for different points?
- It would be better to get new points from user,
right? For this we will use scanf - To use these functions, we need to use
- include ltstdio.hgt
44Standard Output
- printf Function
- prints information to the screen
- requires two arguments
- control string
- Contains text, conversion specifiers or both
- Identifier to be printed
- Example
- double angle 45.5
- printf(Angle .2f degrees \n, angle)
- Output
- Angle 45.50 degrees
Conversion Specifier
Control String
Identifier
45Conversion Specifiers for Output Statements
Frequently Used
46Standard Output
- Output of -145 Output of 157.8926
Specifier Value Printed
f 157.892600
6.2f 157.89
7.3f 157.893
7.4f 157.8926
7.5f 157.89260
e 1.578926e02
.3E 1.579E02
Specifier Value Printed
i -145
4d -145
3i -145
6i __-145
-6i -145__
8i ____-145
-8i -145____
47Exercise
int sum 65 double average 12.368 char ch
b Show the output line (or lines) generated
by the following statements.
- printf("Sum 5i Average 7.1f \n", sum,
average) - printf("Sum 4i \n Average 8.4f \n", sum,
average) - printf("Sum and Average \n\n d .1f \n", sum,
average) - printf("Character is c Sum is c \n", ch, sum)
- printf("Character is i Sum is i \n", ch, sum)
48Exercise (contd)
- Solution
- Sum 65 Average 12.4
- Sum 65
- Average 12.3680
- Sum and Average
- 65 12.4
- Character is b Sum is A
- Character is 98 Sum is 65
49Standard Input
- scanf Function
- inputs values from the keyboard
- required arguments
- control string
- memory locations that correspond to the
specifiers in the control string - Example
- double distance
- char unit_length
- scanf("lf c", distance, unit_length)
- It is very important to use a specifier that is
appropriate for the data type of the variable
50Conversion Specifiers for Input Statements
Frequently Used
51Exercise
- float f
- int i
- scanf(f i, f, i)
- What will be the values stored in f and i after
scanf statement if following values are entered - 12.5 1
- 12 45
- 12 23.2
- 12.1 10
- 12
- 1
52Good practice
- You dont need to have a printf before scanf, but
it is good to let user know what to enter - printf(Enter x y )
- scanf(d d, x, y)
- Otherwise, user will not know what to do!
- What will happen if you forget before the
variable name?
53Exercise How to input two points without
re-compiling the program
printf(enter x1 y1 ) scanf(lf lf, x1,
y1) printf(enter x2 y2 ) scanf(lf lf,
x2, y2)
54Programming exercise
- Write a program that asks user to enter values
for the double variables (a, b, c, d) in the
following formula. It then computes the result
(res) and prints it with three digits after .
55Exercise
- Study Section 2.5 and 2.6 from the textbook
56Name Addr Content
Lecture 6
Lecture
57Library Functions
582.7 Math Functions
include ltmath.hgt fabs(x) Absolute value of
x. sqrt(x) Square root of x, where
xgt0. pow(x,y) Exponentiation, xy. Errors occur
if x0 and ylt0, or if xlt0 and y is not an
integer. ceil(x) Rounds x to the nearest integer
toward ? (infinity). Example, ceil(2.01) is
equal to 3. floor(x) Rounds x to the nearest
integer toward -? (negative infinity).
Example, floor(2.01) is equal to
2. exp(x) Computes the value of
ex. log(x) Returns ln x, the natural logarithm of
x to the base e. Errors occur if
xlt0. log10(x) Returns log10x, logarithm of x to
the base 10. Errors occur if xlt0.
59Trigonometric Functions
sin(x) Computes the sine of x, where x is in
radians. cos(x) Computes the cosine of x, where
x is in radians tan(x) Computes the tangent of
x, where x is in radians. asin(x) Computes the
arcsine or inverse sine of x, where x must be
in the range -1, 1. Returns an angle in
radians in the range -?/2,?/2. acos(x) Computes
the arccosine or inverse cosine of x, where x
must be in the range -1, 1. Returns an angle
in radians in the range 0, ?. atan(x) Computes
the arctangent or inverse tangent of x. The
Returns an angle in radians in the range
-?/2,?/2. atan2(y,x) Computes the arctangent
or inverse tangent of the value y/x. Returns
an angle in radians in the range -?, ?.
60Parameters or Arguments of a function
- A function may contain no argument or contain one
or more arguments - If more than one argument, list the arguments in
the correct order - Be careful about the meaning of an argument. For
example, sin(x) assumes that x is given in
radians, so to compute the sin of 60 degree, you
need to first conver 60 degree into radian then
call sin function - define PI 3.141593
- theta 60
- theta_rad theata PI / 180
- b sin(theta_rad) / is not the same as
sin(theta) /
61Exercise
- Write an expression to compute velocity using the
following equation - Assume that the variables are declared
velocity sqrt(vovo2a(x-xo))
velocity sqrt(pow(vo,2)2a(x-xo))
62Exercise
- Write an expression to compute velocity using the
following equation - Assume that the variables are declared
Make sure that a is given in radian otherwise,
first convert it to radian
center (38.19(pow(r,3)-pow(s,3))sin(a))/
((pow(r,2)-pow(s,2))a)
center (38.19(rrr - sss)sin(a))/((rr
ss)a)
63Exercise Compute Volume
- Write a program to compute the volume of a
cylinder of radius r and height h
r
h
64Solution Compute Volume
- Problem Solving Methodology
- 1. Problem Statement
- 2. Input/Output Description
- 3. Hand Example
- 4. Algorithm Development
- 5. Testing
65Solution Compute Volume (contd)
- Problem Statement
- compute the volume of a cylinder of radius r and
height h - Input Output Description
radius r
volume v
height h
66Solution Compute Volume (contd)
- Hand example
- r2, h 3, v37.68
- Algorithm Development
- Read radius
- Read height
- Compute Volume
- Print volume
- Convert to a program (see next slide)
67Solution Compute Volume (coding)
include ltstdio.hgt define PI 3.141593 int
main(void) / Declare Variables / double
radius, height, volume printf("Enter radius
") scanf("lf",radius) printf("Enter height
") scanf("lf",height) / Compute Volune
/ volume PIradiusradiusheight /
Print volume / printf("Volume 8.3f \n",
volume) system("pause") exit(0)
68Exercise
- Write a program to find the radius of a circle
given its area. Read area from user. Compute
radius and display it.
r
69Exercise
Write a program that asks user to enter A in
degrees, a and b in cm, then computes B? in
degrees C? in degrees c? in cm area?
in cm2
For example, given A36o, a8 cm, b5 cm
B21.55o, C122.45o, c11.49 cm
70Write a program that finds the intersection of
two lines and the angle between them
A1xB1yC10
A2xB2yC20
712.8 Character Functions
include ltctype.hgt putchar(a) C
getchar() toupper(ch) If ch is a lowercase
letter, this function returns the
corresponding uppercase letter otherwise, it
returns ch isdigit(ch) Returns a nonzero value
if ch is a decimal digit otherwise, it returns
a zero. islower(ch) Returns a nonzero value if
ch is a lowercase letter otherwise, it returns
a zero. isupper(ch) Returns a nonzero value if
ch is an uppercase letter otherwise, it
returns a zero. isalpha(ch) Returns a nonzero
value if ch is an uppercase letter or a
lowercase letter otherwise, it returns a
zero. isalnum(ch) Returns a nonzero value if ch
is an alphabetic character or a numeric digit
otherwise, it returns a zero.
72Exercise
What is the output of the following
program include ltstdio.hgt include
ltctype.hgt int main(void) char ch1'a', ch2
char ch3'X', ch4 char ch5'8' ch2
toupper(ch1) printf("c c \n",ch1,ch2) ch4
tolower(ch3) printf("c c \n",ch3,ch4)
printf("d\n",isdigit(ch5)) printf("d\n",islow
er(ch1)) printf("d\n",isalpha(ch5))
system("pause") return(0)
73Skip
- Study Section 2.9 from the textbook
- Skip Section 2.10