Function
Function
C PROG
C Functions A function is a block of code that performs a specific task.
2-User-defined functions
Standard library functions
The standard library functions are built-in functions in C programming.
These functions are defined in header files. For example,
•The printf() is a standard library function to send formatted output to the
screen (display output on the screen). This function is defined in
the stdio.h header file.
Hence, to use the printf()function, we need to include the stdio.h header
file using #include <stdio.h>.
•The sqrt() function calculates the square root of a number. The function is
defined in the math.h header file.
For example, main() is a function, which is used to execute code,
and printf() is a function; used to output/print text to the screen :
Example
int main() {
printf("Hello World!");
return 0;
}
User-defined function
You can also create functions as
per your need. Such functions created by the user are known as user-defined
functions.
Create a Function
To create (often referred to as declare) your own function, specify the name of the
function, followed by parentheses () and curly brackets {}:
Syntax
void myFunction()
{
// code to be executed
}
Function Aspects
void hello()
{
printf("hello c");
}
If you want to return any value from the function, you need to
use any data type such as int, long, char, etc.
int main()
{
myFunction(); // call the function
return 0;
}
A function can be called multiple times:
void myFunction()
{
Example printf("I just got executed!");
}
int main()
{
myFunction();
myFunction();
myFunction();
return 0;
}
#include<stdio.h>
void main ()
{
void printName();
printf("Hello ");
}
void printName()
{
printf(“Ajay");
}
Example for Function without argument and with return value
#include<stdio.h>
void main()
{
int sum();
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Example for Function with argument and without return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Example for Function with argument and with return value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}