Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
36 views
C Programming Functions
Functions in c programming
Uploaded by
Rimuru
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save C programming functions For Later
Download
Save
Save C programming functions For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
36 views
C Programming Functions
Functions in c programming
Uploaded by
Rimuru
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save C programming functions For Later
Carousel Previous
Carousel Next
Save
Save C programming functions For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 18
Search
Fullscreen
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)sreturning 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 TreeTae 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, otherwiseExample: 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 ReferenceCall 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
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6125)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (932)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8214)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Tóibín
3.5/5 (2061)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2641)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Yes Please
From Everand
Yes Please
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel