C Programming for Beginners : Functions

Suraj Das
3 min readNov 5, 2021

--

Photo by Shahadat Rahman on Unsplash

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.)

img 1
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 :

img 2

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 :

img 3

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 :

img 4

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.

img 5

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.

img 6

Now, this divide function calculates the division of two integer types and returns the value to the variable at main function.

Final Code :

img 7

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.

Index of C Programming lessons :

  1. Getting Started within 5 minutes
  2. Learning Fundamentals Made Easy
  3. Circumference and Area of Circle
  4. scanf() vs fgets()
  5. Hypotenuse Calculator
  6. Learn by Building a Calculator
  7. Functions
  8. More on Functions
  9. Length of an Array
  10. String Functions
  11. The While Loop

--

--