1 / 71

Functions and Characters

Functions and Characters. Lone Leth Thomsen. 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.

ewan
Télécharger la présentation

Functions and Characters

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. FunctionsandCharacters Lone Leth Thomsen

  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. 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 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. 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; 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 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; } Basis-C-3/LL

  8. 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; } 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 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 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 Basis-C-3/LL

  12. Basics about functions • 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 Basis-C-3/LL

  13. 1 2 /* Find the maximum of three integers */ 3 #include <stdio.h> 4 5 int maximum( int, int, int ); /* function prototype */ 6 7 int main() 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 */ 19 int 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 } 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 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 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); } 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 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 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 } 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 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 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 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 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 Basis-C-3/LL

  25. Function body 2 { statement_1; statement 2; … statement_n; return expression; } • The function body must be inside { } 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 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; 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 Basis-C-3/LL

  29. Function prototypes 2 • 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 Basis-C-3/LL

  30. Function prototypes 3 • 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 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)); } 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)); } 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 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 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 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) 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 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 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 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 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 Basis-C-3/LL

  42. Call-by-value vs. call-by-reference • 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 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 Basis-C-3/LL

  44. Characters

  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) 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 Basis-C-3/LL

  47. The ASCII Chart Basis-C-3/LL

  48. The char data type 2 • 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 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 “ ” 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 ONEcharacter Basis-C-3/LL

More Related