Chap 2
Chap 2
Simple C Programs
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
1
Name Addr Content
Lecture++;
Lecture 3
2
2.1 Program Structure
3
/*-----------------------------------------*/ Comments
/* Program chapter1_1 */
Preprocessor,
/* This program computes the */
/* distance between two points. */ standard C library
#include <stdio.h> every C program must
#include <math.h> have main function, this
one takes no parameters
int main(void) and it returns int value
{ { begin
/* Declare and initialize variables. */
double x1=1, y1=5, x2=4, y2=7, Variable declarations,
side_1, side_2, distance; initial values (if any)
7
Memory
double x1=1,x2=7,distance;
name address Memory - content
…
11 How many memory cells
does your computer have?
x1 12 1 = 00000001
Say it says 2Gbyte memory?
x2 13 7 = 00000111 1K=103 or 210 = 1024
1M=106 or 220 = 10242
14
1G=109 or 230 = 10243
distance 15 ? = 01001101
16
8
…
Memory Snapshot
9
Rules 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 ^%@)
Case sensitive (AbC, aBc are different)
Cannot use C keywords as identifiers (e.g.,
if, case, while)
10
Are the following valid identifiers?
distance rate% initial_time
x_sum DisTaNce
1x
switch X&Y
x_1
11
C Numeric Data Types
12
Example Data-Type Limits
13
C 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
14
Memory
name address Memory - content
How to represent ‘a’ ?
char My_letter=‘a’;
0
int My_number = 97 My_letter 1 ‘a’= 01100001
Always we have 1’s and 0’s
in the memory. It depends My_number 2 97 = 01100001
on how you look at it?
For example, 01100001 is
3
97 if you look at it as int, or 4
‘a’ if you look at it as char
5 ? = 01001101
‘3’ is not the same as 3 6
How to represent 2.5?
… 15
Program to Print Values as
Characters and Integers
16
Constants
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;
a
char b =‘a’; 01100001
double area, r=2.0; 01100001 b
double circumference;
? area
area = 3.14 * r*r;
circumf
circumference = 2 * 3.14 * r; ? erence
2.0 r
17
Symbolic 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
18
2.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;
0 sum
Example 2
x
int x;
x=5;
5
Example 3
char ch;
ch = ‘a’; ‘a’ ch
19
Assignment examples (cont’d)
Example 3
int x, y, z;
x 0
x = y = 0;
right to left! y 0 2 5
Z = 1+1; z 2
Example 4
y=z;
y=5;
20
Assignment examples with
different types
int a, b=5; ? 2 a
double c=2.3; 5 b
…
2.3 5.0 c
a=c; /* data loss */
c=b; /* no data loss */
long double, double, float, long integer, integer, short integer, char
Data may be lost. Be careful!
No data loss 21
Exercise: swap
Write a set of statements that swaps the
contents of variables x and y
x 3 x 5
y 5 y 3
Before After
22
Exercise: swap
First Attempt
x=y;
y=x;
x 3 x 5 x 5
y 5 y 5 y 5
23
Exercise: swap
Solution
temp= x;
x=y;
y=temp;
x 3 x 3 x 5 x 5
y 5 y 5 y 5 y 3
temp ? temp 3 temp 3 temp 3
Lecture++;
Lecture 4
25
Arithmetic 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 5%2 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
26
Arithmetic Operators (cont’d)
Note that ‘id = exp‘ means assign
the result of exp to id, so
X=X+1 means
first perform X+1 and
Assign the result to X
4 X
Suppose X is 4, and 5
We execute X=X+1
27
Integer division vs Real division
Division between two integers results in an
integer.
The result is truncated, not rounded
Example:
int A=5/3; A will have the value of 1
int B=3/6; B will have the value of 0
To have floating point values:
double A=5.0/3; A will have the value of 1.666
double B=3.0/6.0; B will have the value of 0.5
28
Implement a program that computes/prints
simple arithmetic operations
34
Writing a C statement for a
given MATH formula
Area of trapezoid
base * (height1 height2 )
area
2
38
Step-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
39
Step-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);
40
Exercise: reverse a number
Suppose you are given a number in the
range [100 999]
Write a program to reverse it
For example, int d1, d2, d3, num=258, reverse;
num is 258 d1 = num / 100;
Lecture++;
Lecture 5
42
2.4 Standard Input and Output
Output: printf
Input: scanf
Remember the program computing the distance between
two points!
/* Declare and initialize variables. */
double x1=1, y1=5, x2=4, y2=7,
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 <stdio.h>
43
Standard Output
printf Function
prints information to the screen
requires two arguments
control string
Conversion
Contains text, conversion specifiers or both
Specifier
Identifier to be printed
Output:
Angle = 45.50 degrees
Identifier
44
Conversion Specifiers for
Output Statements
Frequently Used
45
Standard Output
Output of -145 Output of 157.8926
Specifier Value Printed Specifier Value Printed
%i -145 %f 157.892600
%4d -145 %6.2f 157.89
%3i -145 %7.3f 157.893
%6i __-145 %7.4f 157.8926
%-6i -145__ %7.5f 157.89260
%8i ____-145 %e 1.578926e+02
%-8i -145____ %.3E 1.579E+02
46
Exercise
int sum = 65;
double average = 12.368;
char ch = ‘b’;
Show the output line (or lines) generated by the following statements.
47
Exercise (cont’d)
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
48
Standard Input
scanf Function
inputs values from the keyboard
required arguments
control string
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
49
Conversion Specifiers for
Input Statements
Frequently Used
50
Exercise
float f;
int i;
scanf(“%f %i“, &f, &i);
51
Good practice
You don’t 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?
52
Exercise: How to input two points
without re-compiling the program
53
Programming 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 .
55
Name Addr Content
Lecture++;
Lecture 6
56
Library Functions
57
2.7 Math Functions
#include <math.h>
fabs(x) Absolute value of x.
58
Trigonometric Functions
59
Parameters 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); */
60
Exercise
Write an expression to compute velocity using the following
equation
Assume that the variables are declared
velocity = sqrt(vo*vo+2*a*(x-xo));
velocity = sqrt(pow(vo,2)+2*a*(x-xo));
61
Exercise
Write an expression to compute velocity using the following
equation
Assume that the variables are declared
38.19(r s ) sin a
3 3
center
(r 2 s 2 )a
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);
V r h 2
63
Solution: Compute Volume
Problem Solving Methodology
1. Problem Statement
2. Input/Output Description
3. Hand Example
4. Algorithm Development
5. Testing
64
Solution: Compute Volume
(cont’d)
Problem Statement
compute the volume of a cylinder of radius r and
height h
Input Output Description
radius r
volume v
height h
65
Solution: Compute Volume
(cont’d)
Hand example
r=2, h =3, v=37.68
Algorithm Development
Read radius
Read height
Compute Volume V r h
2
Print volume
Convert to a program (see next slide)
66
Solution: Compute Volume
(coding)
#include <stdio.h>
#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 = PI*radius*radius*height;
/* Print volume */
printf("Volume = %8.3f \n", volume);
system("pause");
exit(0);
} 67
Exercise
Write a program to find the radius of a circle
given its area. Read area from user. Compute
radius and display it.
A r 2
68
Exercise
A Write a program that asks user to
enter A in degrees, a and b in cm,
b then computes
c B=? in degrees
C=? in degrees
c=? in cm
B a C
area=? in cm2
For example, given A=36o, a=8 cm, b=5 cm:
a b c B=21.55o, C=122.45o, c=11.49 cm
sin A sin B sin C
1 1 1
area ab sin C ac sin B bc sin A
2 2 2 69
Write a program that finds the
intersection of two lines and the
angle between them
See handout
=0
C
y+
1
x+B 1
A1
A2 x+B
2 y+C =
2 0
70
2.8 Character Functions
#include <ctype.h>
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.
71
Exercise
What is the output of the following program
#include <stdio.h>
#include <ctype.h>
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",islower(ch1));
printf("%d\n",isalpha(ch5));
system("pause");
return(0);
} 72
Skip
Study Section 2.9 from the textbook
Skip Section 2.10
73