Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Functions and Characters Lone Leth Thomsen

2 February 2006Basis-C-3/LL2 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.

3 February 2006Basis-C-3/LL3 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

4 February 2006Basis-C-3/LL4 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.

5 February 2006Basis-C-3/LL5 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;

6 February 2006Basis-C-3/LL6 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

7 February 2006Basis-C-3/LL7 Lasagna ala C #include 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; }

8 February 2006Basis-C-3/LL8 Lasagna ala C void 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; }

9 February 2006Basis-C-3/LL9 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

10 February 2006Basis-C-3/LL10 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

11 February 2006Basis-C-3/LL11 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

12 February 2006Basis-C-3/LL12 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

13 February 2006Basis-C-3/LL13 1 2 /* Find the maximum of three integers */ 3#include 4 5int maximum( int, int, int ); /* function prototype */ 6 7int main() 8{8{ 9 int a, b, c; 10 11 printf( "Enter three integers: " ); 12 scanf( "%d%d%d", &a, &b, &c ); 13 printf( "Maximum is: %d\n", maximum( a, b, c ) ); 14 15 return 0; 16} 17 18/* Function maximum definition */ 19int maximum( int x, int y, int z ) 20{ 21 int max = x; 22 23 if ( y > max ) 24 max = y; 25 26 if ( z > max ) 27 max = z; 28 29 return max; 30}

14 February 2006Basis-C-3/LL14 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

15 February 2006Basis-C-3/LL15 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

16 February 2006Basis-C-3/LL16 Example #include 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); }

17 February 2006Basis-C-3/LL17 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

18 February 2006Basis-C-3/LL18 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

19 February 2006Basis-C-3/LL19 Function definitions A function definition has two principal components –The function header Including parameter declarations –The body of the function function_header { function_body }

20 February 2006Basis-C-3/LL20 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

21 February 2006Basis-C-3/LL21 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

22 February 2006Basis-C-3/LL22 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

23 February 2006Basis-C-3/LL23 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

24 February 2006Basis-C-3/LL24 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

25 February 2006Basis-C-3/LL25 { statement_1; statement 2; … statement_n; return expression; } The function body must be inside { } Function body 2

26 February 2006Basis-C-3/LL26 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

27 February 2006Basis-C-3/LL27 “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 ;

28 February 2006Basis-C-3/LL28 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

29 February 2006Basis-C-3/LL29 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

30 February 2006Basis-C-3/LL30 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

31 February 2006Basis-C-3/LL31 Example #include #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)); }

32 February 2006Basis-C-3/LL32 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)); }

33 February 2006Basis-C-3/LL33 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

34 February 2006Basis-C-3/LL34 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

35 February 2006Basis-C-3/LL35 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

36 February 2006Basis-C-3/LL36 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)

37 February 2006Basis-C-3/LL37 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

38 February 2006Basis-C-3/LL38 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

39 February 2006Basis-C-3/LL39 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

40 February 2006Basis-C-3/LL40 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

41 February 2006Basis-C-3/LL41 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

42 February 2006Basis-C-3/LL42 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

43 February 2006Basis-C-3/LL43 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

44 Characters

45 February 2006Basis-C-3/LL45 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)

46 February 2006Basis-C-3/LL46 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

47 February 2006Basis-C-3/LL47 The ASCII Chart

48 February 2006Basis-C-3/LL48 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

49 February 2006Basis-C-3/LL49 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 “ ”

50 February 2006Basis-C-3/LL50 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

51 February 2006Basis-C-3/LL51 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

52 February 2006Basis-C-3/LL52 Characters or numbers int a=65; char b=65; printf("%d %c %d %c", a, a, b, b); 65 A

53 February 2006Basis-C-3/LL53 Character arithmetic Since all characters have a value, it actually makes sense to perform some aritmetic operations on them.

54 February 2006Basis-C-3/LL54 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

55 February 2006Basis-C-3/LL55 Ascii characters Print the ASCII values for the printable characters #include int main(void) { int i; printf(“ASCII character \n”); for (i = 32; i < 127; i++) printf(“%d\t %c\n”, i, i); }

56 February 2006Basis-C-3/LL56 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)

57 February 2006Basis-C-3/LL57 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

58 February 2006Basis-C-3/LL58 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 library, where EOF is also defined –#define EOF (-1)

59 February 2006Basis-C-3/LL59 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

60 February 2006Basis-C-3/LL60 A function to echo characters void echo(void) { char c; c = getchar(); putchar(c); } Example

61 February 2006Basis-C-3/LL61 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

62 February 2006Basis-C-3/LL62 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; }

63 February 2006Basis-C-3/LL63 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

64 February 2006Basis-C-3/LL64 The classification functions All Characters ControlPrintable SpaceGraphical Punctuation Alphanumeric Alpha Numeric Upper Case Lower Case iscontrol( ) isprint( ) isspace( ) isgraph( ) ispunct( ) isalnum( ) isalpha( ) isdigit( ) isupper( ) islower( )

65 February 2006Basis-C-3/LL65 Character Macros from ctype.h

66 February 2006Basis-C-3/LL66 Example Program #include 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; }

67 February 2006Basis-C-3/LL67 Example - print codes Read in 5 characters Print the ASCII codes used for these characters Then print the characters

68 February 2006Basis-C-3/LL68 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

69 February 2006Basis-C-3/LL69 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);

70 February 2006Basis-C-3/LL70 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

71 February 2006Basis-C-3/LL71 Example - ToUpper int 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; }


Download ppt "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."

Similar presentations


Ads by Google