250 likes | 331 Vues
Functions. Functions. Every programming language has a way of packaging blocks of code that perform a specific “function” C has…. functions Until now, we have been writing all code in the function main() However as your programs perform ever more complex tasks, the code becomes larger.
E N D
Functions • Every programming language has a way of packaging blocks of code that perform a specific “function” • C has…. functions • Until now, we have been writing all code in the function main() • However as your programs perform ever more complex tasks, the code becomes larger
Functions • As the code becomes larger, it becomes harder to maintain or debug / troubleshoot • Advantages of functions: • Avoid re-writing of code over and over • Dividing code into related functions makes your program logic easier to develop • Bugs are easier to find and fix • Bugs in your program are isolated – they will not affect other parts of the program
Functions • Just as the function main(), all functions have: • A name • A list of parameters that it takes • A return type and • A block of code it executes • The only difference between main() and other functions is that execution of a program starts from main().
Functions • We have been using many function: • printf() • scanf() • getch() • system() • All have a name, a list of arguments, a return type and a block of code that they execute
Functions • The general syntax of a function can be expressed as follows: return_typefunction_name (argument_list….) { …. some code …. return …. ; }
Functions • You can have a function without any arguments or any return value • E.g. if a function only clears the screen and displays a menu on screen then it will not need any arguments or a return value
Functions – Some more properties • The order in which functions are defined does not affect the order in which they can be called • Function cannot be defined inside another function • Any function can be called from any other function • Functions can call hem selves: Recursion • There is no limit on the number of functions in a program • There is no limit on the number of times a function can be called • After completing execution in a function, execution resumes from where the function was called
Example - Functions • Write a function that triples a given number: int triple (int num) • Write a function that divides a given number by 3: intdiv_by_three(int num) • Write a function that raises a given number to 3rd power: intraise_three (int num) • Assign the returned value to another variable • Use the returned value directly in a printf
Function Prototypes • As per convention, we put function declaration/prototypes at the beginning before main() while their definitions at the end. • This is because functions perform smaller tasks while the main() gives structure to the program • It is helpful for the reader to first understand the structure and later go into its implementation details. • It is also a convention to put comments with the prototypes so that the reader knows before hand what these functions do.
Functions – Sequence of execution void display_options(void) { system("cls"); printf("Select an option from the menu below\n"); printf("=================================\n"); printf("1. Triple a number\n"); printf("2. Divide it by 3\n"); printf("3. raise it to 3rd power\n"); printf("4. Exit\n"); } #include <stdio.h> int triple(intnum); void display_options(); int main() { int var_1 = 0, var_2 = 0; printf("Enter a number : "); scanf("%d", &var_1); display_options(); 20. var_2 = triple(var_1); printf("\nThe number %d trippled is %d\n", var_1, var_2); system("pause"); return 0; } inttriple(intnum) { int result = 0; result = 3 * num; return result; }
Functions – Sequence of execution void display_options(void) { system("cls"); printf("Select an option from the menu below\n"); printf("=================================\n"); printf("1. Triple a number\n"); printf("2. Divide it by 3\n"); printf("3. raise it to 3rd power\n"); printf("4. Exit\n"); } #include <stdio.h> int triple(intnum); void display_options(); int main() { int var_1 = 0, var_2 = 0; printf("Enter a number : "); scanf("%d", &var_1); display_options(); 20. var_2 = triple(var_1); printf("\nThe number %d trippled is %d\n", var_1, var_2); system("pause"); return 0; } inttriple(intnum) { int result = 0; result = 3 * num; return result; }
Example – Function to check for a prime number Intis_prime(int num) { intj,flag=0; //flag equals 0 if a number is prime for(j=2;j<=num/2;++j) { if(num%j==0) { flag=1; break; } } return flag; } // We can use this function to find all prime numbers in a // given range of integers
Example - Binary Decimal Conversion intdecimal_to_binary(intn) { intrem, i=1, binary=0; while (n!=0) { rem=n%2; n/=2; binary+=rem*i; i*=10; } return binary; } intbinary_to_decimal(intn) { intdecimal=0, i=0, rem=0; while (n!=0) { rem = n%10; n/=10; decimal += rem*pow(2,i); ++i; } return decimal; }
Scope • Variables in a program have certain properties • Type • Name • Some value at any given time • Storage space (e.g. 4-bytes for int) • Another property of a variable is its scope. • It is the part of a program where a variable is visible
Scope • Recall the example program in which we declared variables inside different blocks. • That is called “block-scope”. • Variables defined inside a function have block scopes • They are visible only inside the functions that they are declared in. • Also called “Local” variables.
Scope • Variables declared outside any function including main() are visible from the point of declaration till the end of file. • Such variables have a “File-scope” and are called “Global” variables. • Global variables are visible to all functions in the file from the point of declaration till the end of file • Global variables should be avoided to the maximum (with the exception of ‘constant’ global variables). They are harder to • Read • understand • Debug • maintain
Scope - Example • Write a function to swap contents of two variables • Test whether you can access variables of one function from another function • Use passing by value • Use global variables
Functions arguments • if a function accepts arguments then the parameters in arguments_list are called “formal parameters” return_typefunction_name (argument_list….) { …. some code …. return …. ; } These variables are formal parameters
Functions arguments • The formal parameters behave like regular variables inside the function and are created upon entry into the function and destroyed upon exit • They are also local variables • When calling a function, arguments can be passed to it in two ways: • Call by value • Call by reference and pointers
Swap variable contents Example • Write a function to swap contents of two variables • First, call a function (by value) twice and see whether variables contain values from first function call into the second function call • Next, use passing by reference (pointers)
Recursion • Function can call themselves • These are called recursive functions • Example – Write a function that builds an n ft wall…. (or just prints that it did)
main() Height = 3; build_wall if(height > 1) { printf("I just built a %d ft wall\n", build_wall(total_ht - 1)); } 2 2 return height; build_wall if(height > 1) { printf("I just built a %d ft wall\n", build_wall(total_ht - 1)); } 1 1 return height; if(height > 1) { build_wall printf("I just built a %d ft wall\n", build_wall(total_ht - 1)); } return height;