Date post: | 02-Jan-2016 |
Category: |
Documents |
Upload: | ralph-turner |
View: | 225 times |
Download: | 1 times |
1
Original Author : Turgay Korkmaz
e-mail: [email protected]: www.cs.utsa.edu/~korkmaz
Revised for ME2008 Spring—(2009_ME2008a_C ( NTUST.ME)
CS 2073Computer Programming w/
Eng. Applications – (ch2)
Simple C Programs
3
Thinking : Q1
1. Problem statement Compute the straight line distance between two points in a
plane2. Input/output descriptionPoint 1 (x1, y1)
Point 2 (x2, y2)Distance between two points (distance)
(x1,y1)
(x2, y2)
URL Source: http://www.cs.utsa.edu/~korkmaz/teaching/cs2073/ ( Ch1).
4
3. Hand example
Example Q1 (cont’d)
22 side2side1distance
22 23distance
22 side2side1distance
61.313distance
side1 = 4 - 1 = 3 side2 = 7 - 5 = 2
5
Example 1 (cont’d)
4. Algorithm development and codinga. Generalize the hand solution and list/outline the
necessary operations step-by-step1) Give specific values for point1 (x1, y1) and point2
(x2, y2) 2) Compute side1=x2-x1 and side2=y2-y13) Compute 4) Print distance
b. Convert the above outlined solution to a program using any language you want (see next slide for C imp.)
22 side2side1distance
7
Example 1 (cont’d)
5. Testing After compiling your program, run
it and see if it gives the correct result.
Your program should print outThe distance between two points is 3.61
If not, what will you do?
8
Modification to Example 1
x1=2, y1=5, x2=10, y2=8,
How will you find the distance between two other points (2,5) and (10,8)?
9
/*-----------------------------------------*//* Program chapter1_1 *//* This program computes the *//* distance between two points. */
#include <stdio.h>#include <math.h>
int main(void){ /* Declare and initialize variables. */ double x1=1, y1=5, x2=4, y2=7,
side_1, side_2, distance;
/* Compute sides of a right triangle. */ side_1 = x2 - x1; side_2 = y2 - y1; distance = sqrt(side_1*side_1 + side_2*side_2);
/* Print distance. */ printf("The distance between the two points is " "%5.2f \n",distance);
/* Exit program. */ system("pause"); return 0;}/*-----------------------------------------*/
Comments
Preprocessor, standard C library
main function: No parameters, return type is int
{ begin
Variable declarations, initial values
Statements
indentation
indentation
return 0
} end of function
10
General Form
preprocessing directives
int main(void)
{
declarations
statements
}
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
11
Another Program/***************************************************//* Program chapter1 *//* This program computes the sum of two numbers */
#include <stdio.h>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);
/* Exit program. */ return 0;}/****************************************************/
12
2.2 Constants and Variables A variable is a memory location
that is assigned a name or an identifier
An identifier is used to reference a memory location.
Memorysnapshot
13
Memory
1 = 00000001
7 = 00000111
? = 01001101
0
1
2
3
4
5
6
…
x1
x2
distance
addressname Memory - content
How many memory cells does your computer have?
Say it says 2Gbyte memory?
1K=103 or 210 = 1024
1M=106 or 220 = 10242
1G=109 or 230 = 10243
14
Rules for selecting a valid identifier (variable name)
Must begin with an alphabetic character or underscore
May contain only letters, digits and underscore (no special characters)
Case sensitive Can not use keywords as identifiers
18
C Character Data Type: char
In memory, everything is stored as binary value, which can be interpreted as char or integer. Examples of ASCII Codes
char result =‘Y’;
19
MemoryHow to represent ‘a’ ?
char My_letter=‘a’;
int My_number = 97
Always we have 1’s and 0’s in the memory, it depends 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_number
address name Memory - content
My_letter
21
Constants A constant is a specific value that we use
in our programs. For example3.14, 97, ‘a’, or “hello”
In your program,int a = 97;char b =‘a’;double area, r=2.0;double circumference;area = 3.14 * r*r;circumference = 2 * 3.14 * r;
01100001
01100001
?
?
2.0
a
b
areacircumference
r
22
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
23
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; Example 2
int x;x=5;
Example 3char ch;ch = ‘a’;
0
5
‘a’
sum x
ch
24
Assignment examples (cont’d) Example 3
int x, y, z;x = y = 0;right to left!Z = 1+1;
Example 4y=z;
y=5;
0
0
2
x
y
z
2 5
25
Assignment examples with different types
int a, b=5;double c=2.3;…a=c; /* data loss */c=b; /* no data loss
*/
?
5
2.3
a
b
c
2
5.0
long double, double, float, long integer, integer, short integer, char
Data may be lost. Be careful!
No data loss
26
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
27
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
Suppose X is 4, and We execute X=X+1
4 X5
28
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 1int 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.666double B=3.0/6.0; B will have the value of 0.5
29
Precedence of Arithmetic OperatorsMixed operations:
int a=4+6/3*2; a=?
int b=(4+6)/3*2; b=?
a= 4+2*2 = 4+4 = 8b= 10/3*2 = 3*2= 6
5 assign = Right to left
30
Exercise Compute the following
2*(3+2) 2*3+2 6-3*2
Area of trapezoid
area = 1.0/2*base*(height_1+height_2);
2
)(* 21 heightheightbasearea
31
Exercise Write a C statement to compute the
following
14.305.0
3.622
23
xx
xxxf
f = (x*x*x-2*x*x+x-6.3)/(x*x+0.05*x+3.14);
gmm
mmTension
21
212 Write a C statement to compute the
following
Tension = 2*m1*m2 / m1 + m2 * g;
Tension = 2*m1*m2 / (m1 + m2) * g
Wrong !!
32
Increment and Decrement Operators
Increment Operator ++ post increment x++; pre increment ++x;
Decrement Operator --
post decrement x--; pre decrement --x;
}x=x+1;
}x=x-1;
But, the difference is in the following example. Suppose x=10;
A = x++ - 5; means A=x-5; x=x+1; so, A= 5 and x=11
B =++x - 5; means x=x+1; B=x-5; so, B=6 and x=11
33
Abbreviated Assignment Operator
operator example equivalent statement += x+=2; x=x+2;-= x-=2; x=x-2;*= x*=y; x=x*y;/= x/=y; x=x/y;%= x%=y; x=x%y;
!!! x *= 4+2/3 x = x*4+2/3 wrongx=x*(4+2/3)
correct
35
Exercise: swap Write a set of statements that swaps
the contents of variables x and y
3 5
x y
5 3
x y
Before After
37
Exercise: swapSolution
temp= x;x=y;y=temp;
3 5
x y
Before
?
temp
3 5
x y
after temp=x
3
temp
5 5
x y
after x=y
3
temp
5 3
x y
after y = temp
3
temp
38
Exercise: reverse a number
Suppose you are given a number in the range [100 999]
Write a program to reverse it For example,
num is 258reverse is 852
int d1, d2, d3, num=258, reverse;
d1 = num / 100;
d2 = num % 100 / 10;
d3 = num % 10;
reverse = d3*100 + d2*10 + d1;
printf(“reverse is %d\n”, reverse);
d1 = num / 100;d3 = num % 10;reverse = num – (d1*100+d3) + d3*100 + d1;
39
Exercise: Arithmetic operations
Show the memory snapshot after the following operations by hand
int a, b, c=5; 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.
?
?
5
?
?
a
b
c
x
y
a = 12 b = 3 c= 5 x = 25.0000 y = 43.0000
40
Exercise: 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);
41
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
42
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 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
Control String
Identifier
Conversion Specifier
45
Standard 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.578926e+02
%.3E 1.579E+02
Specifier
Value Printed
%i -145
%4d -145
%3i -145
%6i __-145
%-6i -145__
%8i ____-145
%-8i -145____
46
Exercise
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);
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 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
50
Exercisefloat 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 112 4512 23.212.1 10121
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
printf(“enter x1 y1: “);
scanf(“%lf %lf“, &x1, &y1);
printf(“enter x2 y2: “);
scanf(“%lf %lf“, &x2, &y2);
55
2.7 Math Functions#include <math.h>
fabs(x) Absolute value of x.
sqrt(x) Square root of x, where x>=0.
pow(x,y) Exponentiation, xy. Errors occur if x=0 and y<=0, or if x<0 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 x<=0.log10(x) Returns log10x, logarithm of x to the base 10.
Errors occur if x<=0.
56
Trigonometric 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 [-, ].
57
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.141593theta = 60;theta_rad = theata * PI / 180;b = sin(theta_rad); /* is not the same as sin(theta);
*/
58
Exercise Write an expression to compute velocity using the
following equation Assume that the variables are declared
)(22 xoxavovelocity
velocity = sqrt(vo*vo+2*a*(x-xo));
59
Exercise Write an expression to compute velocity using the
following equation Assume that the variables are declared
asr
asrcenter
)(
sin)(19.3822
33
center = (38.19*(pow(r,3)-pow(s,3))*sin(a))/ ((pow(r,2)-pow(s,2))*a);
60
Exercise: Compute Volume Write a program to compute the volume
of a cylinder of radius r and height h
hrV 2
h
r
61
Solution: Compute Volume
Problem Solving Methodology
1. Problem Statement
2. Input/Output Description
3. Hand Example
4. Algorithm Development
5. Testing
62
Solution: Compute Volume (cont’d) Problem Statement
compute the volume of a cylinder of radius r and height h
Input Output Description
radius
height
volume
63
Solution: Compute Volume (cont’d) Hand example
r=2, h =3, v=37.68 Algorithm Development
Read radius Read height Compute Volume Print volume
Convert to a program (see next slide)
hrV 2
64
Solution: Compute Volume (cont’d)#include <stdio.h>
#define PI 3.141593
int main(void){ /* Declare Variables */ double radius, height, volume;
/* Get Radius from Keyboard */ printf("Enter radius: \n"); scanf("%lf",&radius);
/* Get Height from Keyboard */ printf("Enter height: \n"); scanf("%lf",&height);
/* Compute Volune */ volume = PI*radius*radius*height;
/* Print volume */ printf("Volume = %8.3f \n",volume);
/* exit program */ system("pause"); exit(0);}
65
Exercise Write a program to find the radius of a
circle given its area. Read area from user. Compute radius and display it.
2rA
r
66
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.
67
ExerciseWhat 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);}