Вы находитесь на странице: 1из 61

Lecture 04

Chapter 2: Overview of C programming(cont..)

Basic Data Types


 int
 used to declare numeric program variables of integer type
 whole numbers, positive and negative
 keyword: int
int number;
number = 12;
 Type of int format

Basic Data Types cont




float
 fractional parts, positive and negative
 keyword: float
float height;
height = 1.72;

Basic Data Types




sign

exponent

mantissa

Basic Data Types cont

Type

Range in Typical Microprocessor


Implementation

short

32,768 .. 32,767

unsigned short

0 .. 65,535

int

2,147,483,648 .. 2,147,483,647

unsigned

0 .. 4,294,967,295

long

2,147,483,648 .. 2,147,483,647

unsigned long

0 .. 4,294,967,295

Basic Data Types cont


 char
 equivalent to letters in English language
 Example of characters:
 Numeric digits: 0 - 9
 Lowercase/uppercase letters: a - z and A - Z
 Space (blank)
 Special characters: , . ; ? / ( ) [ ] { } * & % ^ < > etc
 single character
 keyword: char
char my_letter;
my_letter = 'U';

The declared character must be


enclosed within a single quote!

ASCII Code
 American Standard Code for Information Interchange
 particular code that specifies the integer representing each char





value.
The digit characters '0' through '9' have code values of 48 through
57 (decimal).
uppercase letters have the decimal code values 65 through 90
Lowercase letters have the decimal code values 97 through 122
the printable characters have codes from 32 (code for a blank or
space) to 126 (code for the symbol ~ ).

ASCII Code Table

Extended ASCII Code Table

Constant example volume of a cone


#include <stdio.h>
int main(void)
{
double height, radius, base, volume;
double pi = 3.14;
printf(Enter the height and radius of the cone:);
scanf(%lf %lf ,&height, &radius);
base = pi * radius * radius;
volume = (1.0/3.0) * base * height;
printf(\nThe volume of a cone is %lf , volume);
return 0;
}

#define
 You may also associate constant using #define preprocessor directive

#include <stdio.h>
#define PI 3.14
int main(void)
{
double height, radius, base, volume;
printf(Enter the height and radius of the cone:);
scanf(%lf %lf ,&height,&radius);

base = PI * radius * radius;


volume = (1.0/3.0) * base * height;
printf(\nThe volume of a cone is %lf , volume);
return 0;

Input/Output Operations
 Input operation
 an instruction that copies data from an input device into

memory
 Output operation
 an instruction that displays information stored in memory to

the output devices (such as the monitor screen)

Input/Output Functions
 A C function that performs an input or output operation
 A few functions that are pre-defined in the header file stdio.h

such as :
 printf()
 scanf()
 getchar() & putchar()

The printf function


 Used to send data to the standard output (usually the

monitor) to be printed according to specific format.


 General format:
 printf(string literal);
 A sequence of any number of characters surrounded by double quotation

marks.

 printf(format string, variables);


 Format string is a combination of text, conversion specifier and escape

sequence.

The printf function cont


 Example:
 printf(Thank you);
 printf (Total sum is: %d\n, sum);
 %d is a placeholder (conversion specifier)
 marks the display position for a type integer variable
 \n is an escape sequence
 moves the cursor to the new line

Program Structure: Executable


e.g. sum = sum + item;


Note: Left side of an assignment


statement is called lvalue it must
be assignable
Examples of invalid assignment (result in compilation error lvalue
required as left operand of assignment):
 32 = a;
 a + b = c;
Assignment can be cascaded, with associativity from right to left:
 a = b = c = 3 + 6; // 9 assigned to variables c, b and a
 The above is equivalent to: a = (b = (c = 3 + 6));
which is also equivalent to:
c = 3 + 6;
b = c;
a = b;

Program Structure: Executable




Side Effect:


An assignment statement does not just assigns, it also has the


side effect of returning the value of its right-hand side
expression
Hence a = 12; has the side effect of returning the value of
12, besides assigning 12 to a
Usually we dont make use of its side effect, but sometimes we
do, eg:
z = a = 12; // or z = (a = 12);
The above makes use of the side effect of the assignment
statement a = 12; (which gives 12) and assigns it to z
Side effects have their use, but avoid convoluted codes:
a = 5 + (b = 10); // assign 10 to b, and 15 to a
Side effects also apply to expressions involving other operators
(eg: logical operators).

Escape Sequence
Escape Sequence

Effect

\a

Beep sound

\b

Backspace

\f
\n

Formfeed (for printing)


New line

\r

Carriage return

\t

Tab

\v

Vertical tab

\\

Backslash

sign

\o

Octal decimal

\x

Hexadecimal

\O

NULL

Placeholder / Conversion Specifier


No
1
2
3
4
5
6
7
8

Conversion
Specifier
%d
%i
%o
%u
%x
%X
%f
%e

%E

10
11
12
13

%g
%G
%c
%s

Output Type

Output Example

Signed decimal integer


Signed decimal integer
Unsigned octal integer
Unsigned decimal integer
Unsigned hexadecimal (small letter)
Unsigned hexadecimal (capital letter)
Integer including decimal point
Signed floating point (using e
notation)
Signed floating point (using E
notation)
The shorter between %f and %e
The shorter between %f and %E
Character
String

76
76
134
76
9c
9C
76.0000
7.6000e+01
7.6000E+01
76
76
7
76'

The scanf function


 Read data from the standard input device (usually keyboard)

and store it in a variable.


 General format:
 scanf(Format string, &variable);

 Notice ampersand (&) operator :


 C address of operator
 it passes the address of the variable instead of the variable itself
 tells the scanf() where to find the variable to store the new

value

The scanf function cont


 Example :

int age;
printf(Enter your age: );
scanf(%d, &age);
 Common Conversion Identifier used in printf and scanf

functions.
printf

int
float
double
char
string

%d
%f
%lf
%c
%s

scanf

%d
%f
%lf
%c
%s

The scanf function cont


 If you want the user to enter more than one value, you

serialise the inputs.


 Example:
float height, weight;
printf(Please enter your height and weight:);
scanf(%f%f , &height, &weight);

Few notes on C program cont


 Reserved Words
 Keywords that identify language entities such as statements,

data types, language attributes, etc.


 Have special meaning to the compiler, cannot be used as
identifiers (variable, function name) in our program.
 Should be typed in lowercase.
 Example: const, double, int, main, void,printf, while, for, else
(etc..)

Few notes on C program cont


 Punctuators (separators)
 Symbols used to separate different parts of the C program.
 These punctuators include:
[ ] ( ) { } , ; : * #
 Usage example:
int main void()
{
int num = 10;
printf(%d, num);
return 0;
}

Few notes on C program cont


 Operators
 Tokens that result in some kind of computation or action when

applied to variables or other elements in an expression.


 Example of operators:
*+=-/
 Usage example:

 result = total1 + total2;

Input/Output


%d and %lf are examples of format specifiers; they are placeholders for values to be
displayed or read
Placeholder

Variable Type

Function Use

%c

char

printf / scanf

%d

int

printf / scanf

%f

float or double

printf

%f

float

scanf

%lf

double

scanf

%e

float or double

printf (for scientific notation)

Examples of format specifiers used in printf():


 %5d: to display an integer in a width of 5, right justified
 %8.3f: to display a real number (float or double) in a width of 8,
with 3 decimal places, right justified
Note: For scanf(), just use the format specifier without indicating width,
decimal places, etc.

Input/Output




\n is an example of escape sequence


Escape sequences are used in printf() function for certain special effects or to display
certain characters properly
These are the more commonly used escape sequences:

Escape
sequence

Meaning

Result

\n

New line

Subsequent output will appear on the next line

\t

Horizontal tab

Move to the next tab position on the current line

\"

Double quote

Display a double quote "

%%

Percent

Display a percent character %

Operators
Arithmetic operations




Binary Operators: +, , *, /, % (modulo or remainder)


Left Associative (from left to right)





Unary operators: +,
Right Associative




x = 23

p = +4 * 10

Execution from left to right, respecting parentheses rule, and then precedence
rule, and then associative rule (next page)


46 / 15 / 2  3 / 2  1
19 % 7 % 3  5 % 3  2

addition, subtraction are lower in precedence than multiplication, division, and


remainder

Truncated result if result cant be stored (the page after next)




int n;

n = 9 * 0.5;

results in 4 being stored in n.

Operators


Arithmetic operators: Associativity & Precedence


Operator

Name

Number of
operands

Position

Associativity

Parentheses

Unary

Prefix

Left to right

Parentheses

Unary

Postfix

Left to right

Positive sign

Unary

Prefix

Right to left

Negative sign

Unary

Prefix

Right to left

++

Post-increment

Unary

Postfix

Left to right

--

Post-decrement

Unary

Postfix

Left to right

++

Pre-increment

Unary

Prefix

Right to left

--

Pre-decrement

Unary

Prefix

Right to left

Multiplication, division,
remainder

Binary

Infix

Left to right

Addition, subtraction

Binary

Infix

Left to right

Assignment

Binary

Infix

Right to left

*, /, %
+, =, +=, -=,
*=, /=, %=

Precedence

Operators


Mixed-Type Arithmetic Operations


int
float
int
float
int

m
p
n
q
r

10/4;
means
10/4;
means
10/4.0; means
10/4.0;
means
-10/4.0; means

=
=
=
=
=

Type Casting

Use a cast operator to change the type of an expression


syntax:

(type) expression

int aa =
float pp
int
nn
float qq

6; float ff = 15.8;
= (float) aa / 4;
means
= (int) ff / aa;
means
= (float) (aa / 4); means

Common Programming Errors


 Debugging  Process removing errors from a

program
 Three (3) kinds of errors :
 Syntax Error
 a violation of the C grammar rules, detected during

program translation (compilation).


 statement cannot be translated and program cannot be
executed

Common Programming Errors cont


 Run-time errors
 An attempt to perform an invalid operation, detected

during program execution.


 Occurs when the program directs the computer to
perform an illegal operation, such as dividing a number
by zero.
 The computer will stop executing the program, and
displays a diagnostic message indicates the line where the
error was detected

Common Programming Errors cont


 Logic Error/Design Error
 An error caused by following an incorrect algorithm
 Very difficult to detect - it does not cause run-time

error and does not display message errors.


 The only sign of logic error incorrect program
output
 Can be detected by testing the program thoroughly,
comparing its output to calculated results
 To prevent carefully desk checking the algorithm
and written program before you actually type it

CSE 115: Computing Concepts


Lecture 05:
Chapter 3: Top-Down Design with Functions

Top-Down Design and Structure Charts


 Top down design
 A problem solving method
 break a problem up into its major subproblems
 Solve the subproblems
 Derive the solution

 Structure Charts
 documentation tool
 shows the relationships among the subproblems of a

Drawing Simple Diagrams


 PROBLEM: Draw some simple diagrams on your printer

or screen.

 ANALYSIS: Both figures can be drawn with these four

basic components:
a circle
parallel lines
a base line intersecting lines

Draw a figure
 DESIGN : Divide the problem in three sub problems
 INITIAL ALGORITHM
 Draw a circle.
 Draw a triangle.
 Draw intersecting.

 ALGORITHM REFINEMENTS
 Step 2 Refinement
 2.1 Draw intersecting lines.
 2.2 Draw a base.

Structure Chart

Top down design using function


/* Draws a stick figure*/
#include <stdio.h> /* printf definition */
/* function prototypes */
void draw_circle(void); /* Draws a circle */
void draw_intersect(void); /* Draws intersecting lines */
void draw_base(void); /* Draws a base line */
void draw_triangle(void); /* Draws a triangle */
int main(void)
{
/* Draw a circle. */
draw_circle();
/* Draw a triangle. */
draw_triangle();
/* Draw intersecting lines. */
draw_intersect();
return (0);
}

A simple drawing program


Problem:
- Write a program DrawFigures.c to draw a rocket ship (which is
a triangle over a rectangle, over an inverted V), a male stick
figure (a circle over a rectangle over an inverted V), and a
female stick figure (a circle over a triangle over an inverted V)

rocket

Analysis:

No particular input needed, just draw the needed 3 figures


There are common shapes shared by the 3 figures

Design:

Algorithm (view in words):


1. Draw Rocket ship
2. Draw Male stick figure (below Rocket ship)
3. Draw Female stick figure (below Male stick figure)

male

female

A simple drawing program

Design (Structure Chart):


rocket

Draw 3
Figures
Draw Rocket
Ship
Draw Triangle

Draw
Rectangle

Draw Male
Stick Figure
Draw
Inverted V

Draw Circle

Draw
Rectangle

male

female

Draw Female
Stick Figure
Draw
Inverted V

Draw Circle

Draw Triangle

Draw
Inverted V

Modular Programming
 Break a large problem into smaller pieces
 Smaller pieces sometimes called modules or subroutines or

procedures or functions
 Why?
 Helps manage complexity

Smaller blocks of code


 Easier to read
 Encourages re-use of code
 Within a particular program or across different programs
 Allows independent development of code
 Provides a layer of abstraction


a = sqrt(9.0);

Functions
 The building blocks of a C program
 Youve used predefined functions already:
 main()
 printf(), scanf(), pow()
 User-defined functions
 Your own code
 In combination with predefined functions

Functions - Mathematical View

f ( x) = x 2 + 2 x + 3

What is f(2)?
f (2) (2) 2 + 2(2) + 3 4 + 4 + 3 11
f (2) is 11

Function

Returned
value

f ( x)

11

Functions in C
resultType functionName(type1 param1, type2 param2, )
{

body

}
// functionName
 If no result, resultType should be void
 Warning if not!
 If no parameters, use void between ()

Library Function
 Goal to write error-free code
 Code reuse
 Cs standard math library defines a function named sqrt -

performs the square root computation


 The function call in the assignment statement

C Library Function
Function

Header

Purpose: Example

abs(x)

<stdlib.h> Returns the absolute value of its integer

Argument(s) Result
int

int

argument: if x is 5 , abs(x) is 5

ceil(x)

<math.h>

Returns the smallest integral value that is not


less than x : if x is 45.23 , ceil(x) is 46.0

double

double

cos(x)

<math.h>

Returns the cosine of angle x : if x is 0.0 ,


cos(x) is 1.0

double
(radians)

double

double,
double

double

pow(x,y) <math.h>
sqrt(x)

<math.h>

Returns the nonnegative square root of x (1x)


for x 0.0 : if x is 2.25 , sqrt(x) is 1.5

double

double

log(x)

<math.h>

Returns the natural logarithm of x for x > 0.0 : double


if x is 2.71828 , log(x) is 1.0

double

log10(x)

<math.h>

Returns the base-10 logarithm of x for x > 0.0


: if x is 100.0 , log10(x) is 2.0

double

double

Using Functions
 Let int

f(double x, int a) be (the beginning

of) a declaration of a function.


 Then f(expr1,

expr2) can be used in any expression


where a value of type int can be used e.g.,
N =

+ d;
f(pi*pow(r,2), b+c)

Using Functions
 Let int

f(double x, int a) be (the beginning

of) a declaration of a function.


 Then f(expr1,

expr2) can be used in any expression


where a value of type int can be used e.g.,
N =

+ d;
f(pi*pow(r,2), b+c)

Using Functions (continued)




Let int f(double x, int a) be (the beginning


of) a declaration of a function.
Then f(expr1, expr2) can be used in any
expression where a value of type int can be
used e.g.,
N = f(pi*pow(r,2), b+c) + d;

Function f is executed and returns a


Sum is assigned to N
value of type int

Result of f is added to d

Function definition


Every function definition has the form


return-type function-name (parameter declarations) {
definitions and statements
}

For practical purposes, code between {} (inclusive) is a


compound statement

Function Prototype


There are many, many situations in which a


function must be used separate from where it is
defined
 before

its definition in the same C program


 In one or more completely separate C programs



This is actually the normal case!


Therefore, we need some way to declare a
function separate from defining its body.
 Called

a Function Prototype

Function Prototype (continued)




Definition: a Function Prototype in C is a language


construct of the form:

return-type function-name (parameter declarations) ;

I.e., exactly like a function definition, except with a


';' instead of a body in curly brackets

Purposes of Function Prototype




So compiler knows how to compile calls to that


function, i.e.,



number and types of arguments


type of result

As part of a contract between developer and


programmer who uses the function
As part of hiding details of how it works and
exposing what it does.
A function serves as a black box.

Header files


In applications with multiple C programs, function


prototypes are typically provided in header files
 I.e.,

the .h files that programmers include in their code

Grouped by related functions and features


 To

make it easier for developers to understand


 To make it easier for team development
 To make a package that can be used by someone else

Include


#include <foo.h>
 Search

the systems directories in order for a file of the


name foo.h

#include "foo.h"
 Search

the directory where the source program is found


first, before system directories

Functions - Definition Structure


 Function 'header'
 Return data type
(if any)
 Name

type function_name (type arg1, type arg2 )


{
statements;
}

 Descriptive

 Arguments (or parameter list)


 Notice: data type and name

 Statements
 Variable declaration
 Operations
 Return value (if any)

A function that calculates the product of two numbers


double product(double x, double y)
{
double result;
result = x * y;
return result;
}

Functions - Example


Function prototype
 Like a variable declaration
 Tells compiler that the function will be defined
later
 Helps detect program errors
 Note semicolon!!

Function definition
 See previous slide
 Note, NO semicolon

Function return
 return statement terminates execution of the

current function
 Control returns to the calling function
 if return expression;



then value of expression is returned as the


value of the function call
Only one value can be returned this way

Function call





main() is the 'calling function'


product() is the 'called function'
Control transferred to the function code
Code in function definition is executed

#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
ans = product(var1, var2);
printf("var1 = %.2f\n"
"var2 = %.2f\n",var1,var2);
printf("var1*var2 = %g\n", ans);
}
/* function definition */
double product(double x, double y)
{
double result;
result = x * y;
return result;
}

Creating Function
#include <stdio.h>
#include <math.h>
#define PI 3.14159

double circle_area(double diameter)


{
return pow(diameter/2, 2) * PI;
}

Function
definition

int main(void) {
// identical portion omitted for brevity
// compute weight of a single washer

rim_area = circle_area(d2) - circle_area(d1);


unit_weight = rim_area * thickness * density;
// identical portion omitted for brevity
}

Calling circle_area()
twice.

Creating Function


Components of a function definition


 Header (or signature): consists of return type, function name, and a list of

parameters (with their types) separated by commas


 Function names follow identifier rules (just like variable names)
 May consist of letters, digit characters, or underscore, but cannot begin with a digit

character
 Return type is void if function does not need to return any value
 Function body: code to perform the task; contains a return statement if return

type is not void


Function name

Return type

Parameter

double circle_area(double diameter) {

return pow(diameter/2, 2) * PI;


}

Function body

Programming style


Preferred practice: add function prototype


 Before main() function
 Parameter names may be omitted, but not their type

#include <stdio.h>
#include <math.h>
#define PI 3.14159

Function prototype
double circle_area(double);
int main(void) {
// identical portion omitted for brevity
// compute weight of a single washer

rim_area = circle_area(d2) - circle_area(d1);


unit_weight = rim_area * thickness * density;
// identical portion omitted for brevity
}
double circle_area(double diameter)
{
return pow(diameter/2, 2) * PI;
}

Function
definition