C++ tutorial-C++ Function


C++ Function


A function is a block of code to perform a specific task. A whole program can be divided in to different functions. By using functions you can breakdown a large program in to small parts that each part performs its own specific task. You may find hard to manage the large program, but you are more easy to manage each smaller part. In addition, the code in  a function can be reused in many parts of your program. This will save you a lot of work.

Before you can call a function, you must create it by declaring it. To declare it you must put a return type such as void, int, float, or double followed by the name of function and parentheses. In the example below, we declare a function named ReadName.

Example:
void ReadName()
{
  char *name;
  cout<<"Enter your name: ";
  cin>>name;
  cout << "\nYour name is"<<name;
}

 

Note: if you use void type, your function will return nothing. However, if you use other type, your function will return value of that type. The example below shows you the function (sum) that returns a total value of two integers.

Example:

int sum()
{
    int a=10;

   int b=20;

   int s=a+b;

   return s; //return total value
}

Calling your function

Your function must be called from the main method.

Example:

void ReadName()
{
   char *name;
   cout<<"Enter your name: ";
   cin>>name;
   cout << "\nYour name is "<<name;
}
 
int main()
{
   ReadName();
   return 0;
}
 


Parameters

Parameters are used to pass values to the function. Parameters must be put in parentheses after the name of the function.

void ReadName(char *s)
{
   cout << s;
}
 
void main()
{
   ReadName("Dara");
}

If you want to pass more than one value then you must separate parameters with commas.

void PrintName(char *fname, char *lname)
{
   cout << fname << lname;
}
 
void main()
{
   PrintName("Dara", "Yuk");
}

Recursive Function

In C++ language, you can create a recursive function. A recursive function is a function that can call itself. The recursive function terminates at the base case. In the example below, the base case is that n is equal to 1.

Example:

int fact(int n){ //a recursive function to calculate a factorial value of n.
  if(n==1) return 1;
  return(n*fact(n-1)); 
}


void main(){
  int n;
  cout<<"Enter n:"; 
  cin>>n; 
  cout<<"The factorial value of "<<n<<"is <<fact(n);
 
}



Comments

Troy comment

 Troy

for more C++, C exercises,
please visit http://ccphplusplus.blogspot.com/


2015-05-26



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.