Title: Engineering Problem Solving with C Fundamental Concepts
1Engineering Problem Solving with C Fundamental
Concepts
- Chapter 2
- Simple C Programs
2Overview
- Program Structure
- Constants and Variables
- Assignment Statement
- Standard Input and Output
- Mathematical Function
- Character Function
3Program Structure
4Program Structure - General Form
- preprocessing directives
- int main(void)
-
- declarations
- statements
-
include ltstdio.hgt
eg
include ltmath.hgt
5Program Structure
- Comments begin with the characters / and end
with the characters / - Preprocessor directives give instructions to the
compiler. Provides instructions that are
performed before the program is compiled. - stdioh.h file contains info related to the o/p
statement used in the program. - math.h file contain info related to the
function used in the program to compute a
mathematical function (egsquare root).
6Program Structure - continued
- Every C program contains one function named main.
- Int indicates the function returns an integer
value to the OS. - Void indicates the function is not receiving any
info from OS. - The body of the main function is enclosed by
braces,
7Program Structure - continued
- The main function contains two types of commands
declarations and statements. - Declaration define the memory locations that
will be used by the statements. - It may or may not give initial values to be
stored. - 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
8Header Files
- Information about the functions can be supplied
to the program by using header files - The files have a .h extension
- The header file is added to the program using the
include preprocessor directive - The include directive tells the compiler to read
in another file and include it in your program - The most common header file is stdio.h
9Components of the Lesson
include ltstdio.hgt void main(void)
printf(This is C!)
10Program Structure - First Program
- /
/ - / Program chapter1 /
- /
/ - / This program computes the sum 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)
- / Exit program. /
- return 0
11Constants and Variables
12Constants and Variables
- A constant is a specific value
- A variable is a memory location that is assigned
a name or an identifier - An identifier is used to reference a memory
location. - Rules for selecting a valid identifier
- must begin with an alphabetic character or
underscore - may contain only letters, digits and underscore
(no special characters) - case sensitive thus uppercase letters are
different from lower case letter. - cannot use keywords as identifiers (pg 38, table
2.1). This is because keywords have special
meaning to the C compiler.
13Keywords
14Practice!
15C Data Types
- Integers
- short
- int
- long
- Floating-Point Values
- float
- double
- long double
- Characters
- char
16- short maximum 32767
- int maximum 2147483647
- long maximum 2147483647
- float precision digits 6
- float maximum exponent 38
- float maximum 3.402823e038
- double precision digits 15
- double maximum exponent 308
- double maximum 1.797693e308
- long double precision 15
- long double maximum exponent 308
- long double maximum 1.797693e308
17Symbolic Constants
- Defined with a preprocessor directive that
assigns an identifier to the constant. - Compiler replaces each occurrence of the
directive identifier with the constant value in
all statements that follow the directive - Example
- define PI 3.141593
18Example
include ltstdio.hgt define DAYS_IN_YEAR
365 define PI 3.14159 void mail()
statement
19Practice!
- Give the preprocessor directives to assign
symbolic constants for these - constants
- 1. Speed of light,c 2.99792 X 108 m/s
- 2. Charge of an electron, e 1.602177 X 10-19 C
- Avogadros number, NA 6.022 X 1023 mol-1
- Accelaration of gravity, g 9.8 m/s2
- Unit of length, Unit_length m
- Unit of time, Unit_Time s
20Assignment Statements
21Assignment Statements
- Used to assign a value to a variable/identifier.
- General Form
- identifier expression
- Example 1
- double sum 0 sum
- Example 2
- int x
- x5 x
- Example 3
- char ch
- ch a ch
0
5
a
22Assignment Statements - continued
- Example 3
- int x, y, z
- xy0
- z2 x
-
- y
-
- z
- Example 4
- yz y
0
0
2
2
23Arithmetic Operators
- Addition
- Subtraction -
- Multiplication
- Division /
- Modulus
- Modulus returns remainder of division between two
integers - Example
- 52 returns a value of 1
24Mixed Operation
- Operation between values with different types
- Before operation the value with the lower type is
converted or promoted to the higher type - eg
- Cast operator specify the type change in the
value before the next compuation - eg int sum, count
- float average
- average (float)sum/count
float
converted
int
float
float
float
25Integer Division
- Division between two integers results in an
integer. - The result is truncated, not rounded
- Example
- 5/3 is equal to 1
- 3/6 is equal to 0
26Priority of Operators
- Parentheses Inner most first
- Unary operators Right to left
- ( -)
- Binary operators Left to right
- ( / )
- Binary operators Left to right
- ( -)
27Increment and Decrement Operators
- Increment Operator
- post increment x
- pre increment x
- Decrement Operator - -
- post decrement x- -
- pre decrement - -x
28Increment and Decrement Operators
- If the increment/decrement operator is in prefix
position,the identifier is modified and the new
value is used to evaluate the rest of the
expression. - If the increment/decrement operator is in postfix
position, the old value of the identifier is
used to evaluate the rest of the expression and
then the identifier is modified.
29Example
include ltstdio.hgt void main(void) int i 1, j
1, k , h printf(Before increment i d,
jd, i, j) k i h j
printf(After increment i d, jd, kd,
hd,i ,j , k, h)
30Practice!
- For the following statements find the values
- generated for p and q?
- int p 0, q 1
- p q
- p q
- p q--
- p --q
31Practice
- Assume
- int counter4, a5, b-7, c
- And the arithmetic expression statement
- c a counter - b
- Answer
- counter ? , c ?
32Abbreviated Assignment Operator
- operator example equivalent statement
- x2 xx2
- - x-2 xx-2
- xy xxy
- / x/y xx/y
- xy xxy
33Abbreviated Assignment Operator
- C allows simple assignment statements to be
abbreviated. - xx3 ? x 3
- sumsum x ? sum x
- dd/4.5 ? d / 4.5
- rr2 ? r 2
34(No Transcript)
35Practice!
- Give a memory snapshot after each statement is
executed, assuming that x is equal to 2 and that
y is equal to 4 before the statement is executed.
Also, assume that all the variables are integers. - zxy
- zxy
- xy
- yx
36Standard Input and Output
37Standard Output
- printf Function
- prints information to the screen
- requires two arguments
- control string
- conversion specifier
- Example
- double angle 45.5
- printf(Angle .2f degrees \n, angle)
- Output
- Angle 45.50 degrees
Control string
Conversion specifier
38Standard 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("1f c", distance, unit_length)
- It is very important to use a specifier that is
appropriate for the data type of the variable
39(No Transcript)
40Practice!
- Assume that the integer variable sum contains the
value 65, the double variable average contains
the value 12.368 and that the char variable ch
contains the value '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)
41Practice!
- Write a program to convert from Fahrenheit to
Celsius values. The program should prompt the
user for Fahrenheit value and then accept the
user input (a floating point value). After the
input is read into a variable (called fahr),
convert the Fahrenheit value according to - celsius (5.0 / 9.0) (fahr 32.0)
- In the above program, change the expression (5.0
/ 9.0) to (5 / 9), recompile and run the program,
and study the output. Why is the answer wrong?
42Library Functions
43Library functions
- The library functions are important component of
C programs - The ANSI C standard specifies a minimum set of
library functions to be supplied by all compilers - This is called the C standard library
- The standard library contains functions to
perform disk I/O, string manipulation etc. - The code for the library functions is added to
the program at link time - Using functions for I/O increases flexibility
44Math Functions
- 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.
45Trigonometric 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 -?, ?.
46Character 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. - 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.