Chapter 7: Function
Function: Definition Building block of C program. Group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. We can divide up your code into separate functions. How we divide up your code among different functions is up to us, but logically the division is such that each function performs a specific task. Eg. printf(), scanf(), sqrt(), pow()
Functions Definition
Function Definition Contd..
Calling the function Definition of what the function has to do is given while creating function To use a function, we 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 program control back to the main program. To call a function, we 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.
Example 1: Program to find sum of number
Example 2: program to find greatest number between two number
Example 3: Program to check whether a number is prime or not Program to generate series of nth prime number Program to generate prime number between two nymbers
Function Prototype In some compiler if we are going write user defined function after main() we have to prototype the function. Syntax: datatype function name(date_type, ……..) Provides following information to function The name of the function Return data type Number of arguments that function accepts
Limitation of Return Returns only one value at a time Invalid return return(a+2, b) return(x, y)
Advantages of Function Avoid repetition of codes. Increases program readability. Divide a complex problem into simpler ones. Reduces chances of error. Modifying a program becomes easier by using function. Easy to debug
Categories of Function Library functions Built in function, already written, compiled and placed in c library Eg: printf(), scanf(), sqrt(), pow() …. User defined function Defined and used by programmer according to their requirement
Categories of User Defined Function Depending upon the number of arguments and return types used defined function can be categorized as Function returning value and passing arguments Function returning no value by passing arguments Function returning value and passing no arguments Function returning no value and passing no arguments
Function returning value and passing arguments
Function returning no value by passing arguments
Function returning value and passing no arguments
Function returning no value and passing no arguments Left to you!!!!!!!