Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Functions. A group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a value A sub-program.

Similar presentations


Presentation on theme: "Programming Functions. A group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a value A sub-program."— Presentation transcript:

1 Programming Functions

2 A group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a value A sub-program  when we write our program we always define a function named main  inside main we can call other functions which can themselves call other functions, and so on…

3 Example - Square int main(void) { double num = 0.0, sqr = 0.0; printf("enter a number\n"); scanf("%lf",&num); sqr = square(num); printf("square of %g is %g\n", num, sqr); return 0; } This is a function defined outside main double square(double a) { return a * a; } Here is where we call the function square

4 Why Use Functions? Break the problem into smaller sub-problems  easier to solve complex problems Generalize a repeated set of instructions  we don’t have to keep writing the same thing over and over  printf and scanf are good examples… They make a program much easier to read and maintain

5 So Far Used  printf  scanf  putchar  getchar Wrote  main

6 Function Definition return-type name(parameter-list) { local-variables statements return statement } return-type: int, double, char, void,... parameter-list: type name, type name,..., type name Function variables = parameters + locals prototype

7 Return Statement Return causes the execution of the function to terminate and returns a value to the calling function The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type)

8 Void Sometimes there’s no reason for a function to return a value In these cases, the function return-type should be ‘ void ’ If the ‘ return ’ keyword is used within such a function it exits the function immediately. No value needs be specified

9 Void Calling ‘ return ’ at the end of a function returning void is not obligatory If the function receives no parameters, the parameter list should be replaced by ‘ void ’ (or just nothing)

10 Exercise Write the function int add(int a, int b); The function takes two numbers as its input and returns their sum Write a program that accepts as input two numbers from the user and adds them using the above function (a main function that calls the add function)

11 Solution int add(int a, int b) { return a + b; } int main(void) { int a,b; printf("Please enter two numbers\n"); scanf("%d%d", &a, &b); printf ("%d + %d = %d\n", a, b, add(a, b)); return 0; }

12 Remark int add(int a, int b) { int res; res = a + b; return res; } a + b;

13 Scope A function defines the scope for a variable A variable declared in a function is only visible within that function

14 Scope.c int do_something(void) { int a; printf("Entered do_something\n"); a = 7; printf("In do_something, a = %d\n", a); printf("Exiting do_something\n"); return a; } int main(void) { int res = 0, a = 34; printf("Entered main\n"); printf("In main, a = %d\n", a); res = do_something(); printf("do_something returned %d\n", res); printf("In main, a = %d\n", a); printf("Exiting main...\n"); return 0; }

15 Frames A frame is a structure containing function information at runtime A frame corresponds to a function call  new call → new frame

16 At Runtime double power(double base, int exponent) { int i = 0; double result = 1; for (i = 1; i <= exponent; i++) result = result * base; return result; } int main() { double result = power(2,20) + power(3,15) + power(5,17); printf("2^20 + 3^15 + 5^17= %g", result); return 0; } source codecall stack result main base exponent result i power = 2 = 20 = 3 = 15 = 5 = 17

17 Another Example main foo printf bar main foo printf bar printf

18 Call by Value Function arguments are passed by copying their values rather than giving the function direct access to the actual variables A change to the value of an argument in a function body will not change the value of variables in the calling function

19 Call by Value - Example void multBy5(int b) { b *= 5; } int main(void) { int a = 34, b = 1; multBy5(b); printf("a = %d, b = %d\n", a, b); return 0; } a = 34, b = 1

20 The Right Way int multBy5(int b) { return b *= 5; } int main(void) { int a = 34, b = 1; b = multBy5(b); printf("a = %d, b = %d\n", a, b); return 0; } a = 34, b = 5

21 Exercise “Twin Primes” is a pair of prime numbers whose difference is 2. e.g. (3, 5), (11, 13) Write a program that receives as input a number from the user and outputs all the twins up to (and including) that number. For example: Input: 8 Output: (3, 5) (5, 7)

22 Hands Off The Keyboard!!!

23 How To Approach The problem? Make sure you understand the problem Outline the most simple algorithm for solution What are the subtasks of the solution? – each subtask will be a separate function.

24 Bad Idea #1 for all pairs (i,j) smaller-equal N if twin_primes(i, j) print (i, j)

25 Why Bad? Consider the implementation – Is it simple? – Is it efficient? – Do we really need to go over all pairs? – Do we need to check the pairness of each number twice?

26 Take 2 for all i ≤ N - 2 if (i, i + 2) are primes print (i, i + 2) What about this Solution?

27 Candidate Functions Identify reoccurring tasks in your solution  good candidates to become functions. Are there any in the proposed solution?

28 Prime Identification is_prime(n): for 2 <= i < n if i factor of n return false return true

29 Function Implementation Implement your functions. Try to abstract away from the task at hand. – What is the purpose of the function? – What information it needs to achieve its goal (input arguments) – What is the return value? Implement a function(s) that binds the basic blocks into a complete, specific algorithm. (usually main) – When do we need to use and which function? – What do we need to pass in as arguments? – Where do we store return values?

30 GO

31 Debugger - Reminder F9 – set breakpoint F5 – run in debug mode F10 – step over (execute a single command)  treat functions as single command F11 – step into (for stepping into functions)

32 Twin Primes Solution We’ll use the debugger to go over the solution

33 Function Declaration Most software projects in C are composed of more than one file We want to be able to define the function in one file, and to use it in all files

34 Function Declaration For this reason, the function must be declared in every file in which it’s used, before it is used for the first time the declaration contains (prototype) : return_type Function_name(argument-list);

35 Function Declaration #include /* Contains Standard IO functions declaration! */ int factorial(int a); /* Our Function Declaration! */ int main(void){ int num = 0; printf("enter a number\n"); scanf("%d", &num); printf("%d != %d\n", num, factorial(num)); return 0; } int factorial(int a){ int i, b = 1; for(i = 1; I <= a; i++) b = b*i; return b; }

36 Function Declaration stdio.h actually contains a large set of function declarations The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called

37 /*** *stdio.h - definitions/declarations for standard I/O routines * * Copyright (c) Microsoft Corporation. All rights reserved. * ****/... /* Function prototypes */ _CRTIMP int __cdecl getc(FILE *); _CRTIMP int __cdecl getchar(void); _CRTIMP int __cdecl _getmaxstdio(void); _CRTIMP char * __cdecl gets(char *); _CRTIMP int __cdecl _getw(FILE *); _CRTIMP void __cdecl perror(const char *); _CRTIMP int __cdecl _pclose(FILE *); _CRTIMP FILE * __cdecl _popen(const char *, const char *); _CRTIMP int __cdecl printf(const char *,...); _CRTIMP int __cdecl putc(int, FILE *); _CRTIMP int __cdecl putchar(int); _CRTIMP int __cdecl puts(const char *); _CRTIMP int __cdecl _putw(int, FILE *); _CRTIMP int __cdecl remove(const char *); _CRTIMP int __cdecl rename(const char *, const char *); _CRTIMP void __cdecl rewind(FILE *); _CRTIMP int __cdecl _rmtmp(void); _CRTIMP int __cdecl scanf(const char *,...); _CRTIMP void __cdecl setbuf(FILE *, char *); _CRTIMP int __cdecl _setmaxstdio(int);...

38 The math Library A collection of mathematical functions Need to include the header file math.h ( #include ) Use functions of the library, e.g. double s,p; s = sqrt(p); Declared in math.h : double sqrt (double x);

39 The math library sin(x), cos(x), tan(x)  x is given in radians asin(x), acos(x), atan(x) log(x) sqrt(x) pow(x,y) – x to the power of y. ceil(x), floor(x) …and more

40 Exercise 1.Implement the following functions:  int is_digit(char c); - returns true if the character is a digit, false otherwise.  int is_lower(char c); - returns true if it’s a lowercase character, false otherwise.  int is_upper(char c); - returns true if it’s an uppercase character, false otherwise. 2.Implement a function int what_is_it(char c); The function takes a single character as input and return:  0 – if it’s a digit  1 – if it’s a lowercase letter  2 – if it’s an uppercase letter  -1 – otherwise 3.Write a program that reads characters from the user (until '\n') and converts lowercase letter to uppercase, uppercase to lowercase and digits into spaces. All other characters should be ignored. NOTE: You can define more functions if you find it necessary


Download ppt "Programming Functions. A group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a value A sub-program."

Similar presentations


Ads by Google