User Define Function IN C /C++
Function in C/C++
User Define Function IN C /C++
before we use the function we must learn about some important point about function:
function have three major parts
1) Declaring the Function (Function propotype)
In C++, function prototype is a declaration of function without its body to give compiler information about user-defined function.
for example :
int myfunction(int) // as we see that in function declaration there is no body of function. just have return value as 'int' name as myfunction and parameter type.
2) Calling The function
Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them,
=>Call by Value
=>Call by Reference
(we discuses Reference in other tutorials later)
myfunction(x);
or result=myfunction(x) // if its return a value;
3) defining the function
The part where the statement of the function are written.
for example
myfunction( )
{
----
---
---
}
Example 1:
we make a program which only display the message with the help of function:
#include #include void message(void); // this is simple function definition which have no return value or passing value void main(void) { int x,y; printf("enter the value of x \n"); scanf("%d",&x); message(); // this is calling the function printf("enter the value of y \n"); scanf("%d",&y); message(); // this is calling the function getch(); { void message(void) { printf("\n Your Number is Store \n"); // just display the message }
In above example every time when you enter a number a message appear that your number is store successfully.
Example 1:
we make a program which only get the two number and add these two number using function.
#include #include int addnumber(int , int); // this is the definition of thge function that this function have name addnumber and return integer value void main(void) { int x,y, result; printf("enter the value of x \n"); scanf("%d",&x); printf("enter the value of y \n"); scanf("%d",&y); result=addnumber(x,y) // this is calling the function getch(); { int addnumber(int a, int b) { return(a+b) ; // Return the result of a+b to call function }