The Need of Functions in the World of Programming
Before explaining what actually a function is, I want you to see this code :
This is a program which gives the division of two numbers but allows you to do it twice.
(Pay attention to the image numbers written under the code snap.)
Enter two numbers : 5 2
Divided : 2.50
Enter two numbers : 6 2
Divided : 3.00
Great! It works fine.
But don’t you think the code is a bit repetitive ? We did the division part twice in this program. So, imagine a scenario where you have to perform the division part 10s or 100s of times. The code will become so much repetitive. Uggh! 😵
Now here comes Functions 😎
Understanding Functions in Programming
Imagine if we could write the above program like this :
We just took our input and passed it into a function called divide.
Yep! It will be giving you an error that says something like this :
undefined reference to `divide'
So what we need to do now is to define the divide function.
Working With a Function
We can define our divide function just above our main function.
Like this :
Do not forget to mention the data type of the function before the function name.
Now this function will do a certain task which will be coded inside those curly braces.
Let’s go back to our imaginary code where we tried to divide two numbers with a divide function. (img 2)
Line 10 :
Here we can see that the divide function takes two arguments i.e., a and b, which are integers.
So we have to set two parameters to our declaration.
This basically means that the divide function will take two integer arguments.
Let’s now state the specific task for our divide function inside those curly braces.
Now, this divide function calculates the division of two integer types and returns the value to the variable at main function.
Final Code :
At line 18, the divide function took two argument which are integers and returned the value to the variable c.
Illustrated explanation :
Great! That’s all for our Functions in C.
Hope you enjoyed this blog.
Have any doubt ?
DM me on Instagram
Peace.