Transcript Document
Simple C Programs
1
Program Structure
preprocessing directives
int main(void)
{
declarations
statements
}
2
Program Structure
Comments begin with the characters /* and end with
the characters */
Preprocessor directives give instructions to the compiler
/* compute distance between two points */
#include <math.h>
Every C program contains one function named main
int main()
{
statements
}
The body of the main function is enclosed by braces {}
3
Program Structure
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
return 0;
4
First Program
Comments
/******************************************************************/
/* Program chapter1
*/
/*
*/
/* This program computes the sum two numbers
*/
Main
function
Statements
Preprocessor Directive
#include <stdio.h>
int main(void)
No semicolon!
{
/* Declare and initialize variables. */
double number1 = 473.91, number2 = 45.7, sum;
/* Calculate sum. */
sum = number1 + number2;
Variable Declarations
/* Print the sum. */
printf(“The sum is %5.2f \n”, sum);
/* Exit program.
return 0;
*/
Exit the program
}
/*************************************************************/
5
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.
Memory
snapshot
6
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
7
Are the following Valid Identifiers?
distance
1x
x_1
rate%
x_sum
switch
initial_time
DisTaNce
X&Y
8
C Numeric Data Types
9
Example Data-Type Limits
10
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
11
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
12
Example
No selicolon!
#define PI 3.141593
int main()
{
int x,y,z;
int a;
int b;
float f1;
double d1;
}
3 variables of type int
a variable of type float
return 0;
13
Assignment Statements
Used to assign a value to a variable
General Form:
identifier = expression;
Example 1
double sum = 0;
Example 2
int x;
x=5;
sum
0
x
5
ch
a
Example 3
char ch;
ch = ‘a’;
14
Assignment Statements
Example 3
int x, y, z;
x=y=0;
z=2;
x
0
y
0
z
Example 4
y=z;
y
2
2
15
Arithmetic Operators
Addition
Subtraction
Multiplication
Division
Modulus
+
*
/
%
sum = num1 + num2;
age = 2007 – my_birth_year;
area = side1 * side2;
avg = total / number;
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
16
Arithmetic Operators
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
5
X
17
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
18
Precedence of Arithmetic Operators
Mixed operations:
a=4+6/3*2; a=?
a= 4+2*2 = 4+4 = 8
b=(4+6)/3*2; b=?
b= 10/3*2 = 3*2= 6
5
assign =
Right to left
19
Priority of Operators
Compute the following
2*(3+2)
2*3+2
6-3*2
Area of trapezoid
area = 0.5*height*(base_1+base_2);
base_1
height
base_2
20
Increment and Decrement Operators
Increment Operator ++
post increment
pre increment
x++;
++x;
}
x=x+1;
Decrement Operator -
post decrement
pre decrement
x--;
--x;
}
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;
so, B=6 and x=11
means x=x+1; B=x-5;
21
Abbreviated Assignment Operator
operator
example
equivalent statement
+=
-=
*=
/=
%=
x+=2;
x-=2;
x*=y;
x/=y;
x%=y;
x=x+2;
x=x-2;
x=x*y;
x=x/y;
x=x%y;
22
Precedence of
Arithmetic Operators (updated)
23
Exercise
Write a C statement to compute the following
x 2 x x 6.3
f 2
x 0.05 x 3.14
3
2
f = (x*x*x-2*x*x+x-6.3)/(x*x+0.05*x+3.14);
24
Exercise
Write a set of statements that swaps the
contents of variables x and y
3
5
5
3
x
y
x
y
Before
After
25
Exercise
First Attempt
x=y;
y=x;
3
5
5
5
5
5
x
y
x
y
x
y
Before
After x=y
After y=x
26
Exercise
Solution
temp= x;
x=y;
y=temp;
3
5
?
3
5
3
5
5
3
5
3
3
x
y
temp
x
y
temp
x
y
temp
x
y
temp
Before
after temp=x
after x=y
after y = temp
27
Standard Input and Output
28
Standard Input and Output
Output:
Input:
printf
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>
29
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
Conversion
Specifier
Control String
double angle = 45.5;
printf(“Angle = %.2f degrees \n”, angle);
Output:
Angle = 45.50 degrees
Identifier
30
Conversion Specifiers for
Output Statements
Frequently Used
31
Standard Output
Output of -145
Output of 157.8926
Specifier
Value Printed
Specifier
Value Printed
%i
-145
%f
157.892600
%4d
%3i
%6i
%-6i
-145
-145
__-145
-145__
%6.2f
%7.3f
%7.4f
%7.5f
157.89
157.893
157.8926
157.89260
%8i
%-8i
____-145
-145____
%e
%.3E
1.578926e+02
1.579E+02
32
Exercise
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);
33
Exercise (cont’d)
Solution
Sum =
65; Average =
Sum =
65
Average = 12.3680
Sum and Average
12.4
65 12.4
Character is b; Sum is A
Character is 98; Sum is 65
34
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
35
Conversion Specifiers for
Input Statements
Frequently Used
36
Exercise
f1 is float and conversion
specifier for float is f
i1 is integer and conversion
specifier for integer is %f
float f1;
int i1;
scanf(“%f %d”,&f1,&i1);
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
12
1
10
37
Program
#include <stdio.h>
int main()
{
float f1;
int i1;
scanf("%f %i",&f1,&i1);
printf("f=%f i=%i\n",f1,i1);
}
system(“pause”);
return(0);
38
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);
User may not know what to do of you have a scanf
statement only
Scanf(“%d %d”, &x, &y);
What will happen if you forget the & before the
variable name?
39
Exercise: Read two points from user
printf(“enter x1 y1: “);
scanf(“%lf %lf“, &x1, &y1);
printf(“enter x2 y2: “);
scanf(“%lf %lf“, &x2, &y2);
40
Library Functions
41
Math Functions
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.
Rounds x to the nearest integer toward (infinity).
Example, ceil(2.01) is equal to 3.
Rounds x to the nearest integer toward - (negative
infinity). Example, floor(2.01) is equal to 2.
Computes the value of ex.
ceil(x)
floor(x)
exp(x)
log(x)
log10(x)
Returns ln x, the natural logarithm of x to the base e.
Errors occur if x<=0.
Returns log10x, logarithm of x to the base 10.
Errors occur if x<=0.
42
Trigonometric Functions
sin(x)
cos(x)
tan(x)
asin(x)
Computes the sine of x, where x is in radians.
Computes the cosine of x, where x is in radians
Computes the tangent of x, where x is in radians.
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 [-, ].
43
Exercise
Write an expression to compute velocity using the following
equation
Assume that the variables are declared
velocity vo2 2a( x xo)
velocity = sqrt(vo*vo+2*a*(x-xo));
44
Exercise
Write an expression to compute velocity using the following
equation
Assume that the variables are declared
38.19(r s ) sin a
center
2
2
(r s )a
3
3
center = (38.19*(pow(r,3)-pow(s,3))*sin(a))/
((pow(r,2)-pow(s,2))*a);
45
Memory Requirement of Types
short: 2 bytes
int: 4 bytes
long: 4 bytes
Floating point Types
16
Integer Types
float: 4 bytes
double: 8 bytes
long double: 12 bytes
0101011111111111
35.216 = 0.35216*102
1
23
8
See chapter2e2.c
46
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.
?
a
?
b
5
c
?
x
?
y
47
Solution
#include <stdio.h>
int main()
{
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;
printf("a = %d b = %d c= %d
%5.4f \n", a, b, c, x, y);
system("pause");
return 0;
}
a = 12 b = 3 c= 5
x = %5.4f y =
x = 25.0000 y = 43.0000
48
Character Functions
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.
Returns a nonzero value if ch is a lowercase letter; otherwise,
it returns a zero.
Returns a nonzero value if ch is an uppercase letter;
otherwise, it returns a zero.
Returns a nonzero value if ch is an uppercase letter or a
lowercase letter; otherwise, it returns a zero.
Returns a nonzero value if ch is an alphabetic character or a
numeric digit; otherwise, it returns a zero.
islower(ch)
isupper(ch)
isalpha(ch)
isalnum(ch)
49
Exercise
Given a 3 digit number in the range [100.999]
Write a program to reverse it
For example,
num is 258, reverse is 852
num is 123, reverse is 321
num is 111, reverse is 111
How to do it
First approach: Swap first and last digit
Second approach: Split number into digits and combine
them in reverse order
50
Exercise continued
Suppose you have number 258
How can you compute the last digit?
How can you compute the first digit?
Divide 258 by 100 and keep integer part
d1 = 258 / 100 -> 2
How can you compute the middle digit?
Find remainder when you divide 258 by 10
d3 = 258 % 10 -> 8
Get the last 2 digits by finding remainder after division by 100
Divide last 2 digits by 10 and keep the integer part
d2 = 258 % 100 / 10 -> 58/10 -> 5
Construct a reverse number with the digits
number2 = d3*100+d2*10+d1 -> 8*100+5*10+2 -> 852
51