Sie sind auf Seite 1von 48

Engineering Problem Solving with C

Fundamental Concepts
Chapter 2
Simple C Programs
Overview
1) Program Structure
2) Constants and Variables
3) Assignment Statement
4) Standard Input and Output
5) Mathematical Function
6) Character Function

Program Structure
Program Structure - General Form
preprocessing directives
int main(void)
{
declarations;
statements;
}

#include <stdio.h>
#include <math.h>
eg
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
#include <stdio.h>
void main(void)
{
printf(This is C!);
}
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
Call library function
printf by using its name
followed by parentheses
The string enclosed in
parentheses are sent
to the library function
C program body
are terminated
with
a semicolon
Terminated with
a semicolon
The function printf requires
that
the string be enclosed in double
quotes
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 double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Practice!
density area Time
xsum x_sum tax-rate
perimeter sec^2 degrees_C
break #123 x&y
count void f(x)
f2 Final_Value w1.1
reference1 reference_1 m/s
C Data Types




Numbers


Integers Floating Points Values
Characters
C Data Types
Integers
short
int
long
Floating-Point Values
float
double
long double

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
C data type
Characters
Char

ASCII Code

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. Speed of light,c =2.99792 X 10
8
m/s
2. Charge of an electron, e = 1.602177 X 10
-19
C
3. Avogadros number, N
A
=6.022 X 10
23
mol
-1
4. Accelaration of gravity, g =9.8 m/s
2


Assignment Statements
Assignment Statements
Used to assign a value to a variable/identifier.
General Form:
identifier = expression;
Example 1
double sum = 0; sum
Example 2
int x;
x=5; x

Example 3
char ch;
ch = a; ch


0
5
a
Assignment Statements - continued
Example 3
int x, y, z;
x=y=0;
z=2; x

y

z



Example 4
y=z; y


0
0
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:





Cast operator specify the type change in the value
before the next compuation
eg: int sum, count;
float average;
average = (float)sum/count
int
float
float
float
float
converted
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 Inner most first
2 Unary operators Right to left
(+ -)

3 Binary operators Left to right
(* / %)

4 Binary operators Left to right
(+ -)

Increment and Decrement Operators
Increment Operator ++
post increment x++;
pre increment ++x;
Decrement Operator - -
post decrement x- -;
pre decrement - -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 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;

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 of Arithmetic and
Assignment Operators
Precedence Operator Associativity
1 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!
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.
1. z=x++*y;
2. z=++x*y;
3. x+=y;
4. y%=x;
Standard Input and Output
Standard 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


Conversion specifier
Control string
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 %f, %e, %E, %g, %G
double %lf, %le, %lE, %lg, %lG
long double %Lf, %Le, %LE, %Lg, %LG


Character Values
char %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.
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.

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 [-, ].


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.
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.

Das könnte Ihnen auch gefallen