C - Functions

C language is a function oriented programming language.
When you develop a program ,you can create your own function or you can use existing functions.
The main advantage of using a function is re usability.

How to use existing functions

main() is also a inbuilt function.
There are some math library functions are included in C. Let's see how can we use such a function from a example.


Output


In the above code i have called the math.h library function inorder to call a inbuild math library function. It is the only alternation i have done to this code rather than the examples i have done before. Also by giving as '%.2f ' I have given a limit to display the float value. If i haven't given a limit,the float value will display fully as you can see below.

And we should call the function to find the output of the input variable 'v '.
Function calling is done at the last printf statement as sqrt(v).

The syntax of declaring a function.

return_type function_name(parameters)

User Defined Functions

User can declare functions in four ways.
  1. A function without return type and without parameters.
  2. A function with return type and without parameters.
  3. A function without return type and with parameters.
  4. A function with return type and with parameters.
I will use the same example in different ways to show you how u can solve the same problem using these four ways I have mentioned above.

A function without return type and without parameters

Write a program to input two numbers and display the total.




void is no return type.We use void when the question is asked just to display the output. Here in the above example it ask to display total. That's why i have used void as the return type.There is no parameters passed through the function.[sum()]
In main function we can call the function name directly.

A function with return type and without parameters.

Write a program to input two numbers and return the total.




This function has a return type.(A return type means a data type like int,float etc..the function with a return type will return a value relevant to the data type mentioned in the function declaration.)
If the function has a return type ,in main method we should call the function within the printf statement.

A function without return type and with parameters.

Write a function to input two numbers and display the total.



In the function declaration it has passed two parameters.
The function name is directly called in the main function because this is a function without a return type.

A function with return type and with parameters.

Write a function to input two numbers and return the total.


This function has a int return type and two parameters have passed to the function.
In main function ,the declared function name is called within the printf statement.



Comments

Popular posts from this blog

Programming with Java

C- Control Structures