C++ Functions





C++ Functions
A function is meant for performing a specified task. The specified task is repeated each time the program calls the function.

Importance of function

It breaks large computing tasks into smaller ones resulting in the reduction of program size. It increases the modularity of the program and reduces code redundancy. Hence, it saves memory space.

Function declaration / function prototype

In c++, all functions must be declared before they are used.

Syntax of function declaration

Return_type function_name (argument list);

Example

Float function_name (…….)
Void function_name (…….)
Int function_name   (………)

Function definition

A function definition introduces a new user_defined function to the program by declaring the type of value it returns and its parameters and specifying the statement that are executed when the junction is called.

General form of function definition

Return_type function_name (argument list)
{
Body of function
}

A program to find the sum of two variables using function.

#include<iostream.h>
#include<conio.h>
Void main ()
{
Int x, y, z;
Int add (int x, int y);
Cout<<”\n enter the value of x and y:”;
Cin>>x>>y;
Z= add(x, y);
Cout<<”\n the result is :”<< z;
getch ();
}
Int add (int x, int y)
{
Return (x+y);
}

Recursive function

A recursive function is a function that makes a call to itself. When a called faction in turn calls another function, a process of ‘chaining’ occurs. Recursion is a special case of this process where a function calls itself as long as the condition is satisfied.
A  program to find the factorial of given number using recursive function.

#include<iostream.h>
#include<conio.h>
Void main ()
{
Int I;
Int factorial (int);
Cout<<”\n enter a number”;
Cin>>n;
Cout<<”/n factorial=”<<factorial (n);
getch ();
}
Factorial (int n)
{
Int fact;
If (n==0)
Return 1;
Else
{
Fact= n* factorial (n-1);
Return fact;
}
}



Related posts:

  1. Switch Statement In C++ Switch statement in c++ C++ provides a multi way decision...
  2. If Statements In C++ If statements in c++ It is used to test the...
  3. Loops in C++ Loops in C++ Loop is used when we want to...
  4. Manipulators In C++ Manipulators Manipulators are operators used with the insertion operator <<...
  5. If Else Statement In C++ If else statement in c++ Its general form is:- If...