71
Functions and Characters Lone Leth Thomsen

Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

  • View
    214

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

Functionsand

Characters

Lone Leth Thomsen

Page 2: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 2

Lasagna al forno (Kurt Nørmark)

• Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp oil. • Process the pasta in the pasta machine • Melt 3 tblsp butter, mix with 3 tblsp flour. • Add 5 dl milk and bring to boil slowly. • Fry 2 chopped onions with 500 g minced beef, salt and

pepper. • Add 3 tblsp tomato puree, a tin of skinned tomatoes and 3

cloves of garlic. • Boil the meat sauce for 10 minutes. • Mix pasta, meat sauce and white sauce in layers. Sprinkle

with parmesan.• Grill the dish in the oven 15 minutes at 225 C.

Page 3: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 3

Structured lasagna

• A more structured recipe would contain smaller recipes for lasagna plates, white sauce and meat sauce– Lasagna– Lasagna plates– White sauce – Meat sauce

Page 4: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 4

Lasagna

• Make a double portion of lasagna plates.

• Make a portion of white sauce.

• Make a portion of meat sauce

• Mix pasta, meat sauce and white sauce in layers. Sprinkle with parmesan.

• Grill the dish in the oven 15 minutes at 225C.

Page 5: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 5

Make a double portion of lasagna plates

• Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp oil. • Process the pasta in the pasta machine

Make a portion of white sauce• Melt 3 tblsp butter, mix with 3 tblsp flour.

• Add 5 dl milk and bring to boil slowly;

Page 6: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 6

Make a portion of meat sauce

• Fry 2 chopped onions with 500 g minced beef, salt and pepper;

• Add 3 tblsp tomato puree, a tin of skinned tomatoes and 3 cloves of garlic;

• Boil the meat sauce for 10 minutes

Page 7: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 7

Lasagna ala C #include <stdio.h>

void make_lasagne_plates(void); void make_white_sauce(void); void make_meat_sauce(void);

int main(void) { make_lasagne_plates(); make_white_sauce(); make_meat_sauce(); mix plates, meat sauce, and white sauce; sprinkle with parmesan cheese; bake 15 minutes at 225 degrees; return 0;

}

Page 8: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 8

Lasagna ala Cvoid make_lasagna_plates(void) {

mix flour, eggs, salt and oil; process the pasta in the pasta machine;

}

void make_white_sauce(void) { melt butter and stir in some flour; add milk and boil the sauce;

}

void make_meat_sauce(void){ chop the onion, and add meat, salt and pepper; add tomatoes and garlic; boil the sauce 10 minutes;

}

Page 9: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 9

Lesson to be learned

• Using smaller recipes increases the level of abstraction and makes it possible to reuse basic recipes.

• The smaller recipes are like procedures or functions in programming languages. Using parameters generalises a recipe, making it more useful and reusable

Page 10: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 10

Procedures and functions• A procedure is an abstraction over a sequence of

commands

• A function is an abstraction over an expression

• A procedure definition encapsulates a number of commands

• A procedure call is in itself a command

• En function definition encapsulates exactly one expression

• A function call is in itself an expression

Page 11: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 11

Some terminology

• Functions in C– No distinction between procedures and functions, all functions– Modules in C– Programs combine user-defined functions with library functions

• C standard library has a wide variety of functions

• Function calls– Invoking functions

• Provide function name and arguments (data)• Function performs operations or manipulations• Function returns results

Page 12: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 12

• Functions– Modularize a program– All variables declared inside functions are local variables

• Known only in function defined

– Parameters• Communicate information between functions• Local variables

• Benefits of functions– Manageable program development– Software reusability

• Use existing functions as building blocks for new programs• Abstraction - hide internal details (library functions)

– Avoid code repetition

Basics about functions

Page 13: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 13

12 /* Find the maximum of three integers */3 #include <stdio.h>45 int maximum( int, int, int ); /* function prototype */67 int main()8 {9 int a, b, c;1011 printf( "Enter three integers: " );12 scanf( "%d%d%d", &a, &b, &c );13 printf( "Maximum is: %d\n", maximum( a, b, c ) );1415 return 0;16 }1718 /* Function maximum definition */19 int maximum( int x, int y, int z )20 {21 int max = x;2223 if ( y > max )24 max = y;2526 if ( z > max )27 max = z;2829 return max;30 }

Page 14: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 14

What is a function

• It’s a self contained program fragment that carries out a specific well-defined task

• In C, one function in a program has to be called main– Program execution starts by carrying out

instructions contained in main

• If a program contains multiple functions their definitions may appear in any order

Page 15: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 15

How does a function work

• When a function is invoked/called, program control is transferred to this function

• When a function has carried out its intended action, control is returned to the point from which the function was accessed

• A function processes information passed to it from the calling portion of a program, then returns a single value

• Some functions do not return anything

Page 16: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 16

Example#include <stdio.h>

int add(int a, int b);{

int sum;sum = a + b;return sum;

}

int main (void){

int x=4, y=20, z;z = add(x,y);printf(“%d \n”, z);

}

Page 17: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 17

Function design

• Basic idea of functions is to divide code up into small, manageable chunks

• One way to get started designing functions:– Write out the entire program with no functions– Look for sections of code that are almost

exactly duplicated– Create one function for each repeated section

and replace each repetition with the function call

Page 18: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 18

Function design 2

• Look for places where several lines of code are used to accomplish a single task and move the code into a function

• No function too small • Rule of thumb: no function (including

main) should be longer than a page – Goal: be able to see entire function at once

when editing program

Page 19: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 19

Function definitions

• A function definition has two principal components– The function header

• Including parameter declarations

– The body of the function

function_header{

function_body}

Page 20: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 20

Function header

r_type f_name(type_1 prm_1, type_2 prm_2, …, type_n prm_n)

• Allowed data types

– int, long int, float, double, long double, char, void

• Procedures declare the r_type as void

• Functions declare the r_type as a known data type, e.g. int, char, or double

• In procedures and functions without parameters the parameter list is declared as void

Page 21: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 21

Function parameters

• Variables declared in a function header are also called parameters

• Variables passed to a function when it is invoked are also called function arguments

• The number, order and type of parameters in the parameter list of a function definition must be identical to the function call arguments

Page 22: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 22

Function parameters 2

• A function can have any number of parameters (also none). Parentheses must always be used, independent of the number, e.g.value = next_index();

• The same variable name can be used both in the function call and the function definition because they have different scope

• The scope of a variable is defined to be the region of a program where that variable declaration is active

Page 23: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 23

Declarations vs. Definitions

• Both functions and variables MUST be declared before they can be used

• Declaration includes just:• Type• Name• Args (for functions)

• Definition can come later!– For variables: value can be assigned later (as long as it

is before the first use)– For functions: body of function can be added later

Page 24: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 24

Function body

• The body of a function is a compound statement defining the actions to be taken by the function

• The body can contain expression statements, control statements etc.

• The body can access other functions. It may also access itself (recursion)

• The body must include at least one return statement in order to return a value to the calling portion of the program

Page 25: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 25

{statement_1;statement 2;

…statement_n;return expression;

}

• The function body must be inside { }

Function body 2

Page 26: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 26

return statements

• A return statement causes the program logic to return to the point in the program that accessed the function

return expression;

• A function definition can include multiple return statements, each containing a different expression, which are executed depending on the program logic and specific conditions

Page 27: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 27

“No return”

• A void type is used when a function does not return a value back to the calling function

• For a void function

void f_name(…);

the “matching” return statement is simply

return;

Page 28: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 28

Function prototypes

• The main() function should be placed at the beginning of a program

• main() is always the first part of a program to be executed

• Function calls (within main) are bound to precede the corresponding function definitions. Compilation errors can be avoided by using a construct known as a function prototype

Page 29: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 29

• Function prototypes are placed at the beginning of a program (before main) and are used to inform the compiler of name, data type, and number and data types of the arguments of all user defined functions used in the program

• One purpose is to establish the type of arguments a function is to receive and the order in which to receive them

Function prototypes 2

Page 30: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 30

• Example– The prototype for a simple add function is

int add(int a, int b);

– This indicates that add has an integer return value and two arguments

• Since we use ANSI C, the following is also allowed

int add(int , int); // argument names not mandatory

Function prototypes 3

Page 31: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 31

Example

#include <stdio.h>#define PI = 3.14

/* function prototypes */double find_circumference(double r); double find_area(double r);

void main(void){

double radius = 3.7;printf(“Area = %.2f\n”, find_area(radius));

}

Page 32: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 32

Example 2// Computes the circumference of a circle with radius r

double find_circumference(double r){

return (2.0 * PI * r);}

// Computes the area of a circle with radius r

double find_area(double r){

return (PI * pow(r,2));}

Page 33: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 33

Important rules

• All variables and functions must be declared in the function/file where they are going to be used BEFORE they are used

• All variables must be initialized to some starting value before being used in calculations or being printed out

Page 34: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 34

Function modules

• It is common practice to create a separate header file providing the function prototypes

• Header files are as always recognised by .h• The file name is enclosed in “ ” when the header

file is included#include “myheaderfile.h”

• The header file may contain elements appropriate for the “full” program, i.e. #include statements and #define statements

Page 35: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 35

Why type?

• Why do we have to specify types of variables, functions, arguments?

• Different kinds of data require different amounts of memory to store– A single character can have only one of 128 values (a-

z,A-Z,0-9,punctuation, some others)– An integer can have an infinite number of values,

limited to ~65,000 values on a computer– Therefore, more memory needed to store an integer

than a character

Page 36: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 36

Parameters vs. arguments

• Definition: argument is a value received by a called function

• Definition: parameter is the value passed by the caller

• Why the distinction?

• Actually two separate variables when passing by-value (aka calling by value)

Page 37: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 37

Call-by-value

• In call-by-value, when you pass a parameter, its value is copied into a new memory location: the argument

• Any changes to the argument within the called function only affect the argument, not the parameter

• Remember: variables only have meaning within the function where they are declared

• Think of arguments as variables declared in the called function they are received by, with same value as the parameters passed by the caller

Page 38: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 38

Advantages

• This allows us to write a single-valued argument as an expression, rather than being restricted to a single value

• In cases where the argument is a variable, the value of this variable is protected from changes which take place within the function

Page 39: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 39

Disadvantages

• Information cannot be transferred back to the calling portion of the program via arguments

• Call-by-value is a one-way method of transferring information

Page 40: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 40

Call-by-reference

• When calling (passing) by reference, an argument is just a temporary alias for the parameter

• Both the argument and the parameter use the same memory location

• Changing the argument then changes the parameter

• No built-in way to do pass-by-reference in C• Have to use pointers

Page 41: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 41

Reference Operator

• Add in argument declarations to make the argument be called/passed by-reference– Call-by-value: int func(int arg1);– Call-by-reference: int func(int &arg1);

• In the second case, any changes made to arg1 in the function will also impact the parameter in the caller

• Best if used only when you specifically want call-by-reference

Page 42: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 42

• Used when invoking functions• Call by value

– Copy of argument passed to function– Changes in function do not effect original– Use when function does not need to modify argument

• Call by reference – Passes original argument– Changes in function effect original– Only used with trusted functions

• For now, we focus on call-by-value• More later when we talk about pointers

Call-by-value vs. call-by-reference

Page 43: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 43

Scope rules

• Block scope – Identifiers declared inside a block

• Block scope begins at declaration, ends at right brace

– Used for variables, function parameters (local variables of function)

– Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner block

• Function prototype scope – Used for identifiers in parameter list

Page 44: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

Characters

Page 45: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 45

The char data type

• The type char represents single characters– E.g. char b = ‘z’;

• Characters are enclosed in ‘ ’• Declared using

char variable_name;

• Holds one character (i.e a-z, A-Z, 0-9, etc).• Uses one byte of storage• Like a small integer (values 0 to 255)

Page 46: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 46

The ASCII Code

• American Standard Code for Information Interchange

• Each character is assigned a code (number)• These codes are the numbers in a char variable• ASCII codes go from 0 to 127• 0-31 are control codes, the rest are printable

characters• Extended ASCII has 256 values• Æ, Ø, and Å are in the extended set• The standard table is on p. 609 in the book

Page 47: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 47

The ASCII Chart

Page 48: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 48

• E.g the letter A can be declared as a character variable by writing

char letter;letter = ‘A’;

• The quotes are important• There is no relationship between the value of the

character constant representing a digit and the digits integer value

• E.g the value of ‘5’ is NOT 5

The char data type 2

Page 49: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 49

char

• \ is called the escape character– Used to specify that a special character follows– E.g. \n meaning newline

• Characters are enclosed in ‘ ’ but strings are enclosed in “ ”

Page 50: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 50

Characters are not strings

• “A” is stored and treated differently than ‘A’

• The former is stored as two bytes 65 and 0

• The latter is stored as 65 only

• “abc” is a legal string

• ‘abc’ is illegal -- a char variable or constant is always only ONE character

Page 51: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 51

Char constants and variables

char c1, c2;

c1 = 'A'; /* 65 assigned to c1 */

c2 = 65; /* same thing */

printf("%c %c %c", c1, c2, 65);

the output is:

A A A

Page 52: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 52

Characters or numbers

int a=65; char b=65;

printf("%d %c %d %c", a, a, b, b);

65 A 65 A

Page 53: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 53

Character arithmetic

• Since all characters have a value, it actually makes sense to perform some aritmetic operations on them.

Page 54: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 54

Examples

• Adding a number to a char: – ’0’ + 5 == ’5’– The char 5 positions further ahead in the ASCII chart

• Also holds for subtraction• Subtracting 2 chars:

– ’a’ –’A’– The ”distance” between lower and upper case letters

• Comparing 2 chars: – ’a’< ’b’ – Alphabetical ordering

Page 55: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 55

Ascii characters• Print the ASCII values for the printable characters

#include <stdio.h> int main(void) {

int i; printf(“ASCII character \n”);

for (i = 32; i < 127; i++)printf(“%d\t %c\n”, i, i);

}

Page 56: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 56

Non-printing and hard to print char constants

• \b = backspace (move left by one)• \n = new line ( c = ‘\n’; is ok, two symbols

represent only one character, ASCII 10)• \t = tab character (ASCII 9) (advance to next tab)• \r = return (to beginning of current line)• \” = double quote (or c = ‘”’;)• \\ = backslash character

– (c =‘\’; doesn’t work, c=‘\\’; must be used)

Page 57: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 57

Character input/output

• getchar() for input, i.e reading a character• putchar() for output, i.e writing a character • This means we have two options for reading a

character– scanf(“%c”, &ch);– ch = getchar();

• If the program uses a variable to read in characters and test for EOF, the variable should be an int, not a char

Page 58: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 58

getchar()

• getchar() reads one character typed at the keyboard and returns it’s ASCII code as an integer

• when the end of a stream of input characters is reached it returns the EOF (End of File, crtl-Z from keyboard) value

• getchar() is prototyped in the <stdio.h> library, where EOF is also defined– #define EOF (-1)

Page 59: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 59

putchar(char c)

• This function prints the character c to the screen

• Thus getchar() and putchar() are similar to scanf() and printf(), except they just do simple, unformatted single character i/o

Page 60: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 60

• A function to echo characters

void echo(void)

{

char c;

c = getchar();

putchar(c);

}

Example

Page 61: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 61

Example 2

• Get 5 characters from the keyboard

• Print them back to screen

• Note that the Windows Console echos what is typed.

• Only after 'Enter' is pressed, is this input given to your program

Page 62: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 62

Example cont.

int main(void){

char c1, c2, c3, c4, c5;c1 = getchar(); /* read in the 5 characters */c2 = getchar();c3 = getchar();c4 = getchar();c5 = getchar();

/* and print them */printf("\n\n%c%c%c%c%c", c1, c2, c3, c4, c5);return 0;

}

Page 63: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 63

The classification functions

• Because there are so many types of characters, the C language has added the classification functions, which allow testing of a character to see what type the character falls in

• All classification functions begin with is• All classification functions take an integer (which

is actually your character) and return true if the character matches the test

Page 64: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 64

The classification functionsAll

Characters

Control Printable

Space Graphical

Punctuation Alphanumeric

Alpha Numeric

UpperCase

LowerCase

iscontrol( )

isprint( )

isspace( )

isgraph( )

ispunct( )

isalnum( )

isalpha( )

isdigit( ) isupper( )

islower( )

Page 65: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 65

Character Macros from ctype.h

Character macrosMacro Nonzero (true) is returned ifisalpha ( c ) c is a letterisupper ( c ) c is an uppercase letterislower ( c ) c is a lowercase letterisdigit ( c ) c is a digitisalnum ( c ) c is a letter or a digitisxdigit ( c ) c is a hexadecimal digitisspace ( c ) c is a white space characterispunct( c ) c is a punctuation characterisprint( c ) c is a printable characterisgraph ( c ) c is printable, but not a spaceiscntrl ( c ) c is a control characterisascii ( c ) c is an ASCII code

Page 66: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 66

Example Program

#include <stdio.h>

int main(void)

{

int c;

printf ( “Enter an uppercase character (A-Z):” );

scanf ( “ %c” , &c);

if ( isupper (c ))

printf( “Thank you” );

else

printf ( “%c is NOT an uppercase character!” , c );

return 0;

}

Page 67: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 67

Example - print codes

• Read in 5 characters

• Print the ASCII codes used for these characters

• Then print the characters

Page 68: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 68

int main(void) {char c1, c2, c3, c4, c5;

c1 = getchar(); c2 = getchar(); /* get the chars */ c3 = getchar(); c4 = getchar(); c5 = getchar(); /* print as integers, i.e. their ASCII codes */ printf(“\n\n%4d%4d%4d%4d%4d”, c1, c2, c3, c4, c5); /* print as characters */ printf(“\n\n%4c%4c%4c%4c%4c”, c1, c2, c3, c4, c5); return 0;}

Example - print codes 2

Page 69: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 69

Character Conversion Functions

• C also has 2 character conversion functions, which operate on Alpha characters

• toupper changes a character to uppercase

• tolower changes a character to lowercase

int toupper (int);

int tolower (int);

Page 70: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 70

Change to caps

• Change input letters to caps

• Difference between lower case and upper case is 32 for all letters (in English)

• ‘a’ – ‘A’ has value 32

• ‘z’ – ‘Z’ also has value 32

Page 71: Functions and Characters Lone Leth Thomsen. February 2006Basis-C-3/LL2 Lasagna al forno (Kurt Nørmark) Mix 500 g flour, 5 eggs, a pinch of salt, 2 tblsp

February 2006 Basis-C-3/LL 71

Example - ToUpperint main(void) {

char c1,c2,c3,c4,c5;c1 = getchar(); c2 = getchar(); /* get the chars */

c3 = getchar(); c4 = getchar(); c5 = getchar(); /* convert to UC and print */ printf("\n\n%c%c%c%c%c", toupper(c1), toupper(c2), toupper(c3),

toupper(c4), toupper(c5)); /* print as characters */

return 0;}