Transcript Title

Engineering Problem Solving with C
Fundamental Concepts
Chapter 2
Simple C Programs
Overview
1)
2)
3)
4)
5)
6)
Program Structure
Constants and Variables
Assignment Statement
Standard Input and Output
Mathematical Function
Character Function
Program Structure
Program Structure - General Form
preprocessing directives
int main(void)
{
declarations;
statements;
}
#include <stdio.h>
eg
#include <math.h>
Program 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
(eg:square root).
Program 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, { }
Program 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
Header 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”
Components of the Lesson
Preprocessing directive
This file has information about the library
function
printf has that we have used in our program
The terms void indicate that
nothing is received from
the operating system and
nothing is return to the
operating system.
The beginning and
end of the body
The mandatory name
for
the first function to be
executed is main
The function printf requires
that
the string be enclosed in double
#include <stdio.h>
quotes
void main(void)
Terminated the
C program body
{
body with
are terminated
printf(“This is C!”);
a semicolon
with
}
a semicolon
Call library function
printf by using its name
followed by parentheses
The string enclosed in
parentheses are sent
to the library function
Program Structure - First Program
/******************************************************************/
/* Program chapter1
*/
/*
*/
/* This program computes the sum 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;
}
/***************************************************************************/
Constants and Variables
Constants 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.
Keywords
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
Practice!
density
xsum
perimeter
break
count
f2
reference1
area
x_sum
sec^2
#123
void
Final_Value
reference_1
Time
tax-rate
degrees_C
x&y
f(x)
w1.1
m/s
C Data Types
 Integers
 short
 int
 long
 Floating-Point Values
 float
 double
 long double
 Characters
 char
short maximum: 32767
int maximum: 2147483647
long maximum: 2147483647
float precision digits: 6
float maximum exponent: 38
float maximum: 3.402823e+038
double precision digits: 15
double maximum exponent: 308
double maximum: 1.797693e+308
long double precision: 15
long double maximum exponent: 308
long double maximum: 1.797693e+308
Symbolic 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
Example
#include <stdio.h>
#define DAYS_IN_YEAR 365
#define PI 3.14159
void mail()
{
statement;
}
These preprocessor
directives cause
DAYS_IN_YEAR and
PI to be replaced with 365
and 3.14159, respectively
in the source code
Practice!
Give the preprocessor directives to assign symbolic constants for these
constants:
1.
2.
3.
4.
5.
6.
Speed of light,c =2.99792 X 108 m/s
Charge of an electron, e = 1.602177 X 10-19 C
Avogadro’s 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’
Assignment Statements
Assignment Statements

Used to assign a value to a variable/identifier.

General Form:
identifier = expression;

Example 1
double sum = 0;

Example 2
int x;
x=5;

sum
x
0
Example 3
char ch;
ch = ‘a’;
ch
5
a
Assignment Statements - continued
 Example 3
int x, y, z;
x=y=0;
z=2;
x
y
z
0
0
 Example 4
y=z;
y
2
2
Arithmetic Operators





Addition
Subtraction
Multiplication
Division
Modulus


+
*
/
%
Modulus returns remainder of division between two
integers
Example
5%2 returns a value of 1
Mixed Operation
 Operation between values with different types
 Before operation the value with the lower type is converted or
promoted to the higher type

eg:
int
converted
float
float
float

float
Cast operator – specify the type change in the value
before the next compuation

eg: int sum, count;
float average;
average = (float)sum/count
Integer 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
Priority of Operators
1 Parentheses
2 Unary operators
(+ -)
Inner most first
Right to left
3 Binary operators
(* / %)
Left to right
4 Binary operators
(+ -)
Left to right
Increment and Decrement Operators
 Increment Operator ++


post increment
pre increment
x++;
++x;
 Decrement Operator - 

post decrement
pre decrement
x- -;
- -x;
Increment 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.
Example
#include <stdio.h>
void main(void)
{ int i = 1, j = 1, k , h;
printf(“Before increment: i = %d, j=%d”, i, j);
k= i++;
h= ++j;
printf(“After increment: i =%d, j=%d, k=%d,
h=%d”,i ,j , k, h);
}
Output:
Before increment : i = 1, j = 1
After increment: i = 2, j = 2, k=1, h = 2
Practice!
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;
Practice
 Assume :


int counter=4, a=5, b=-7, c;
And the arithmetic expression statement:
c = a % counter++ - b;
Answer:
counter = ? , c = ?
Abbreviated Assignment Operator
operator
+=
-=
*=
/= x/=y;
%=
example
equivalent statement
x+=2;
x-=2;
x*=y;
x=x+2;
x=x-2;
x=x*y;
x=x/y;
x%=y;x=x%y;
Abbreviated Assignment Operator
 C allows simple assignment statements to
be abbreviated.
 x=x+3;  x += 3;
 sum=sum + x;  sum += x;
 d=d/4.5;  d /= 4.5;
 r=r%2;  r %=2;
Precedence
1
Precedence of Arithmetic and
Assignment Operators
Operator
Associativity
Parentheses: ()
Innermost first
2
Unary operators
+ - ++ -- (type)
Right to left
3
Binary operators
*/%
Left to right
4
Binary operators
+-
Left to right
5
Assignment operators
= += -= *= /= %=
Right to left
Practice!

1.
2.
3.
4.
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.
z=x++*y;
z=++x*y;
x+=y;
y%=x;
Standard Input and Output
Standard Output
 printf Function
 prints information to the screen
 requires two arguments
 control string
 conversion specifier
 Example
Control string
double angle = 45.5;
printf(“Angle = %.2f degrees \n”, angle);
Output:
Angle = 45.50 degrees
Conversion specifier
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("%1f %c", &distance, &unit_length);
 It is very important to use a specifier that is appropriate for the data
type of the variable
TABLE 2.6 & 2.7 Conversion Specifiers
for Input & Output Statements
Variable Type
Specifier
Integer Values
int
%i, %d
short
%hi, %hd
long int
%li, %ld
unsigned int
%u
unsigned short
%hu
unsigned long
%lu
Floating-Point Values
float
double
long double
char
%f, %e, %E, %g, %G
%lf, %le, %lE, %lg, %lG
%Lf, %Le, %LE, %Lg, %LG
Character Values
%c
Practice!
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);
Practice!

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?
Library Functions
Library 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
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.
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 [-, ].
Character Functions
toupper(ch)
it returns ch
isdigit(ch)
islower(ch)
isupper(ch)
isalpha(ch)
or a
isalnum(ch)
character
zero.
If ch is a lowercase letter, this function returns the
corresponding uppercase letter; otherwise,
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
lowercase letter; otherwise, it returns a zero.
Returns a nonzero value if ch is an alphabetic
or a numeric digit; otherwise, it returns a