Functions in C Programming — PBA Institute Tutorial
Chapter 11 · C Programming Series
10 min read Beginner

Functions in C

A function in C is a block of code that performs a specific task. It can take inputs, process them, and produce outputs. Functions provide a way to organize code into manageable pieces, promote reusability, and enhance the readability of programs.

What is a Function?

Syntax of a Function

  • A function in C follows a basic syntax : return_type function_name(parameters) {   // function body }
  • return_type : The type of value the function returns to the calling code. It can be 'void' if the function doesn't return anything.
  • function_name : The name of the function, which is used to call it from other parts of the program.
  • parameters : Any values passed to the function for processing. These are optional.
  • function body : The block of code that defines what the function does.

Function Calls

To use a function, you simply call it by its name, passing any required arguments inside parentheses. For example : Calling the add function with arguments 3 and 4
int result = add(3, 4);

Return Statement

Void Functions

Examples

C Code
#include <stdio.h>
int add(int a, int b)
{
	return a+b;
}
main() {
    int result = add(3,4); 
    printf("Add=%d", result);
}
Output
Add=7
In this example :
- 'add' is the name of the function.
- 'int' before the function name specifies the return type of the function. In this case, the function returns an integer.
- 'int a' and 'int b' are the parameters passed to the function.
- Inside the function body, 'a' and 'b are added together, and the result is returned using the return statement.
- In the main function, 'add(3, 4)'' is called, and the result is stored in the result variable.
- Finally, the 'printf' function is used to print the sum.
Write a program to accept a number and check whether number is Even or odd, usin
#include<stdio.h>
void check(int n)
{
	int t,r,s;
	if(n%2==0)
	printf("Even");
	else
	printf("Odd");
}
main()
{
	int n,t;
	printf("Enter a number=");
	scanf("%d",&n);
	check(n);
}
Output
Enter a number=4
Even
Write a program to find the sum of any ten natural numbers, using the function n
#include<stdio.h>
void sum(int n)
{
	int s=0,i;
	for(i=1;i<=n;i++)
	{
		
		s=s+i;
	}
	printf("sum=%d",s);
}
main()
{
	sum(10);
}
Output
sum=55
Write a program to print the last digit of given number , using the function las
#include<stdio.h>
void lastdigit(int n)
{
	int i;
	i=n%10;
	printf("last digit is=%d",i);
}
main()
{
	int n,i;
	printf("enter a number=");
	scanf("%d",&n);
	lastdigit(n);
}
Output
enter a number=123
last digit is=3

Conclusion

Functions are fundamental building blocks in C programming, offering modularity, reusability, abstraction, maintainability, scalability, readability, performance optimization, encapsulation, and information hiding. Mastering the use of functions is essential for writing efficient, robust, and maintainable C programs.