Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

C Programming Functions

Functions in c programming

Uploaded by

Rimuru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
36 views

C Programming Functions

Functions in c programming

Uploaded by

Rimuru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
x C Programming Functions ‘A function is a group of statements that togeth program has at least one function, which is mal programs can define additional functions. er perform a task. Every C in(), and all the most trivial ‘A function is a block of code that performs a specific task ‘Suppose, a program related to graphics needs to create a circle and color it depending upon the radius and color from the user. You can create two functions to solve this problem: = create a circle function + color function Defining a Function The general form of a function definition in C programming language is as follows — return_type function nane( paraneter Tist ) { body of the function A function definition in C programming consists of a function header and ‘a function body. Here are all the parts of a function — = Return Type — A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired out returning a value. In this case, the return_type is the operations keyword void. «Function Name - This is the actual name of the function. The function name and the parameter list together constitute the function signature. es — o the parameter. This value Is referred to as actual ent, The parameter list refers to the type, order, and ters of a function. Parameters are optional; that Is, 2 you pass a value t parameter or argum number of the paramet function may contain no parameters. «Function Body ~ The function body contains a collection of statements that define what the function does. am ) gunct } ae 2 Example for a function called max(). This function \ a eee et \d num2 and returns the maximum value takes two parameters num1 ani 7 between the two — : /* function returning the max between two nunbers */ | : \ int max(int num, int num2) { /* local variable declaration */ int result; if (num. > num2) result = num; else result = num; return result; t Function Declarations A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts — return_type function nane( paraseter 14st ; For the above defined function max(), the function declaration is as follows — Ant max int num, int nun); Parameter names are not important in function declaration only their ype is required, so the following is also a valid declaration — fnt maxCint, int); n is required when you define a function in one source Function declaratiot uld file and you call that function in another file. In such case, you sho declare the function at the top of the file calling the function. Calling a Function While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the progrem control back to the main program. To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example — eee Hinclude /* function declaration */ int max(int numi, int num2); int main () { /* local variable definition */ int a = 1005 int b = 2003 int ret; /* calling a function to get max value */ ret = max(2, B)s returning the max between to nunbers */ rum, int num2) { variable declaration */ sult; > numa) uma ; We have kept max() along with main() and complied the source code, Wnile running the final executable, it would produce the following result max value is : 260 Function Arguments If 2 function is to use arguments, it must declare variables the values of the arguments. These variables are called parametersof the function. that accept the format Formal parameters behave like other local variables inside th i le Function and are created upon entry into the function and destroyed up, On exit, While calling a function, there are tw passed to a function — Sr.No. Call Type & Description 1 Call by value TT his method copies the actual value of an argument into the formal Parameter of the function. In this case, changes made to the parameter Inside the function have no effect on the argument. : Call by reference Thi a method copies the address of an argument into the formal E ‘ameter. Inside the function, the address is used to access the actual Tgument used in the call, This means that changes made to the Parameter affect the argument. By defa aa ate a call by value to pass arguments. In general, it means the unction cannot alter the arguments used to call the function. Types of function Depending on whether a function is defined by vy the user or alread) ‘luded compilers, there are two types of functions in C programming ° There are two types of function in C programming: * Standard library functions + User defined functions Standard library functions The standard library functions are built-in functions in C programming to handle tasks such as mathematical computations, /O processing, string handling etc. These functions are defined in the header file. When you include the header file, these functions are available for use. For example: is the screen is a standard library function to send formatted output to bassiey oie ). This function is defined in "stdio.h* header file (display output on the screen) jer “stdio.h, such inctions defined und s library func “stdio.h” in your program, There are other numerou: x as scanf(), fprintf(), getchar() etc. Once you include all these functions are available for use. in C programming more about standard library funcl Learn User-defined function ‘As mentioned earlier, C allow programmers tO define functions. Such functions created by the user are called user-defined functions. You can create as many user-defined functions as you want How user-defined function works? #include void functionName() { d int main() { functionName() ; When the compiler encounters FunctionNane(); inside the main function, control of the program jumps to void functionName() And, the compiler starts ©xecuting the codes inside the user-defined function. The control of the program Jams to statement next to functionNane(); once all the Codes inside the function definition are executed. Advantages of user-defined function J. The program will be easier to understand, maintain and debug 2. Reusable codes that can be used in other programs 3. A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers, 4. #include 5. 6. int addNumbers(int a, int b); // function prototype Z 8. int main() of 10. int n1,n2, sum; 11. 12. printf("Enters two numbers: 2B. scanf("%d %d",&n1,&n2) ; 14. ; a 15 sum = addNumbers(n1, n2); /1 function ca: 16. 17. printf("sum = %d", sum); ato _ : 1. i as, return 0; 7 7 = tb) // function definition ve i nt 22. int addNumbers(int a, i 23 | 24. int result; | 25. result = a*bj 26. return result; // return statement 2.) Function prototype ‘A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body. ‘A function prototype gives information to the compiler that the function may later be Used in the program, Syntax of function prototype returnType functionName(type1 argumenti, type2 argument2,. In the above example, int addvunbers(int a, int b); is the function which provides following information to the compiler. ae 1. name of the function is adaWunbers() 2. return type of the function is int 3. two arguments of type int are passed to the function The function prototype is not needed if the user-defined function is defined before the main() function Calling a function Control of the program is transferred to the user-defined function by calling it. Syntax of function call functionName(argumenti, argument2, . In the above example, function call is made usin Q ddNunberss{n1,n2); inside the main(), 19 addtiunbers(nt,n2); statement Function definition tic tains the block of code to ere if case, adding two numbers and returning it. oD ‘Syntax of function definition Feturntype functionName(typer argument, type2 argument2, .. { //body of the function Passing arguments to a function In programming, argument refers to the variable passed to the function. In the above example, two variables n1 and n2 are passed during function call The parameters a and b accepts the passed arguments in the function definition, These arguments are called formal parameters of the function The type of arguments passed to a function and the formal parameters must match, otherwise the compiler throws error. If nt is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float type. ‘function can also be called without passing an argument. Return Statement terminates the ex« ym control and returns a value to ction ecution of ay the calling function after The return statement a red to th the calling function. The progral is transfe return statement. variable sum in In the above example, the value of variable result |S returned to the the main() function. Passing Arguments to a function Arguments are the values specified during the function call, for which the formal parameters are declared while defining the function. Functions | With Arguments Without Arguments | | _ declared and defined with [No parameters included. parameter list | values for parameter — No value passed during passed during call aoe L_te: | fe: 1/ declaration // declaration int display(); int sum (int , int y); I call Meall display(); sum(10, 20}; Type of User-defined Functions in C There can be 4 different types of user-defined functions, they are: 1. Function with no arguments and no return value 2. Function with no arguments and a return value 3. Function with arguments and no return value 4 Function with arguments and a return value Below, we will discuss about all these types, along with program examples. Function with no arguments and no return value Such functions can either be used to display information or they are completely dependent on user inputs. Below is an example of a function, which takes 2 Numbers as input from user, and display which is the greater number Corey void greatnum(y ig PU ae ease at iret anya SAGE CLA Sar Spy aCe Et ean eae ttt ean, Function with no arguments and a return value We have modified the above example to make the function greatnum() return the number which is greater amongst the 2 input numbers. rents) Poe Or Pet ee tet oe Ce FaaCTLTe) ( eR teen eT Se oT a ee eee ee) 1 eee Ce fi greaterNum = j; Ta et ee Function with arguments and no return value We are using the same function as example again and again, to demonstrate that to solve a problem there can be many different ways. This time, we have modified the above example to make the function greatum() take two intvalues as arguments, but it will not be returning anything seca Cociie i nie uae rus ramen} ti Tree Tae tMum(int x, ant y) Comoe ue eat ee De ect eee Function with arguments and a return value This is the best type, as this make! e kes the function completely independent of inputs and outputs, and only the logic is defined inside the function int greatNum(int a, int b); EUCanESur6) cr Lar emer os Petree cee Sec nc oF Peer eLcit ease Peete Cee Dey L Pr ena cm ene ton Roa Pererigece tie Uae me UL) { Cee \ Nesting of Functions C language also allows nesting of functions i.e to use/call one function inside another ted functions, because it may lead to function's body. We must be careful while using nes! infinite nesting. Pastas} it Castor Tfunction2() also has a call for function) inside tt, then in that case, it will lead to an infinite nesting. They will Keep calling each other and the program will never terminate. Not able to understand? Lets consider that inside the main() function, function1() is called and its execution starts, then inside functior1(), we have a call for function2(), so fhe control of program will goto the function2(). But as function2() also has a call to function! () in ts body, it will call function1(), which wil again call function2), and this will go on for infinite times, until you forcefully ext from program execution What is Recursion? Recursion is a special way of nestin must have certain conditions in the function to break out recursion will occur infinite times. 19 functions, where a function calls itself inside it. We of the recursion, otherwise Example: Factorial of a number using Recursion (seers Nhs RECS SCRE) DUS mnt aE) torial(a); Ceca yy b= Pune iren eta) is Tra Types of Function calls in C Functions are called by their names, we all know that, then what is this tutorial for? Well if the function does not have any arguments, then to call a function you can directly use its name. But for functions with arguments, we can call a function in two different ways, based on how we specify the arguments, and these two ways are 1. Call by Value 2. Call by Reference Call by Value on Calling a function by value means, we pass the eee f Hl Stored or copied into the formal parameters of the func! 7 7 are unchanged only the parameters inside the function chang! arguments which are lence, the original values SCS e(int Pam le) t cars cote } Picea acacia co pect Pretec ene st Mae se Qi Tora ct ner) value of x in calc function is 2 value of x in main is 1¢ In this case, the actual variable x is not changed. This is because we are passing the argument by value, hence a copy of x is passed to the function, which is updated during function execution, and that copied value in the function is destroyed when the function ends(goes out of scope). So the variable x inside the wain() function is never changed and hence, still holds a value of 10. But we can change this program to let the function modify the original x variable, by making the function calc() return a value, and storing that value in x. CoS err aS Furares eu raeo Faeyr} value of x is 20 Call by Reference ass the address(reference) he address of any variable as argu! ow knows where it is store of a variable as argument to any iment, then the function will .d and hence can easily In call by reference we P: function, When we pass have access to our variable, as it n update its value his case the formal parameter can be take fe will soon learn about them), Int 1 as a reference or a pointer(don't worry about pointers, w in both the cases they will change the values of the original variable. cans Ureerc CoS Reartetaculaat on Fura rule) { aaa Pre ee erie taco STs kUanda Pen woe Peo by void calc(int *P) i } value of x ts 28 y The najore difference between Actual & onal on peenents | Parameters in that Aactuah arguments are he Se infermasion \ calling programs paw Acktwod ae +0 Called cteona Were Vales are parsed toa called ction the Volues preeaent cn actuol angen ute copied 40 Forcmat orgoments > When a ‘function CX carttoal, tre Voluak Mat ace barsedh intro CAML Aire calles thro actual orgemens At the Lime of Cate ent, actuod leaps €4& arrignesl to Correrpondi fren, povrameterc “ Sesion ignition 1 4 \" ZO am Rg CAA At = 10, %5 220, Cteny Actuch « Sum = add nos Ci ,n2)) / fen corer ; « : eee, Prat fC Sumo} 7.4 and Yd ia! za\n) Mas ' int add nos Cit a , tat D) - mater ars the wrocedva Valet kp org, Romance ¢ Pp pen cr RE iif

You might also like