- Get link
- X
- Other Apps
Function in C
C enables programmers to break up a program into segments commonly known as functions, each of which can be written more or less independently of the others.Every function in the program is supposed to perform a well define task. Therefore, the program code of one function is completely insulated from the other functions. Every function interfaces to the outside world in terms of how information is transferred to it and how results generated by the function are transmitted back from it.This interface is basically specified by the function name.C supports two type of function user defined functions and library functions. While main() is a user defined function, printf() and scanf() are library functions. The differenc between a library function and user-defined function is that we as programmers do not have to write the code to implement the library function whereas we need to code the user-defined function to perform a well defined task.
Why are Functions needed
Why Functions are needed?Let us analyse the reason for segmenting a program into manageable chunks as it is an important aspects to programming.
- Dividing the program into separate well-defined function facilitates each function to be written and tested separately. This simplifies the process of getting the total program to work.
- Understanding, coding, and testing multiple separate functions are far easier than doing the same for one huge function.
- If a big program has to be developed without the use of any function other than main(), then there will be countless lines in the main() and maintaining this program will be very difficult. A large program size is a serious issue in micro-computers where memory space is limited.
- All the libraries in C contain a set of functions that the programmers are free to use in their program these function have been pre-written and pre-tested, so the programmers can use them without worrying about their code details.
- When a big program is broken into comparatively smaller functions, then different programmers working on that project can divide the workload by writing different function.
- Like C libraries, programmers can also write their function and use them from different points in the main program or any other program that needs its functionalities.
Write a program to add two integers using functions
#include<stdio.h>
// FUNCTION DECLARATION
int sum(int a, int b);
int main()
{
int num1,num2,total = 0;
printf("\n Enter the first number:");
scanf("%", &num1)
printf("\n Enter the second number:");
scanf("%d", &num2);
total=sum(num1,num2);
// FUNCTION CALL
printf("\n Total= %d", total);
return 0;
}
//FUNCTION DEFINATION
int sum (int a, int b)
{
int result;
result= a+b;
return result;
}
OUTPUT
Enter the first number: 20
Enter the second number:30
Total =50
Comments
Post a Comment