Functions in C
For Complete YouTube Video: Click Here
In this class, we will try to understand Functions in C.
We have already covered the concept of Operators, Selection Statements, Iterative Statements, and Arrays.
Functions in C
The functions are very frequently used in programming.
Functions help to divide the program into small pieces, and they also allow us to avoid duplicating code that is used more than once.
The definition states that functions help to divide the program into small pieces.
This feature of function is used when we write an extensive program with more functionalities involved.
For example, if we want to write a program for the university.
In such programs, we have many functionalities involved, like calculating attendance, calculating marks, and many more.
Then each functionality is divided into a separate function to avoid confusion in writing the program.
The definition also states that functions are used to avoid duplicate code.
To understand this, we will consider the program in the image below.
The above program adds variables a and b at three different levels marked in red.
Here the same line of code is used again and again.
In such a case, we use functions to avoid duplicate code.
The image below is the modified program with the use of functions.
In the above program, we have defined the sum(x, y) function to add a and b.
How to define and declare a function we will try to understand in our later classes.
The top black line in the program shows the function call.
Whenever a function call is made, variables a and b values are transferred to the sum function.
The values of a and b are stored in x and y of the sum function.
In the sum function, x and y will get added, and the result is stored in z.
At the end of the sum function, the return statement will return the z value to the function call represented in the bottom black line.
Similarly, all the function calls are made to avoid duplicate code.